Lab 7a – Writing Contents of Array to File

Log into and navigate to your csci101/labs directory in your repository.  Create a directory named lab7 and change your working directory to lab7.

Create a file named and in it, write a program that satisfies the following specifications.

Inside the class (but after the main method) write a method named printArray that takes an array of integers as an argument.  The method uses a for-loop to print to the screen (on a single line with spaces between them) the elements in the array that is passed to the method.

In the main method, do the following:

    • Print to the screen “Writing Contents of Array to File”.
    • As the user to enter an integer, read the integer from the keyboard, and store the value in a variable named size.
    • Declare an array of integers whose length is equal to the value in the variable named size.
    • Populate the entire array with random values between 1 and 100.
    • Print the contents of the array to the screen using the printArray method.
    • Create an instance of the PrintWriter class that can write to a file named random.txt.
    • Write the value in the variable named size onto the first line of random.txt.
    • Write the contents of the array onto the next line of random.txt with spaces between the values.
    • Close the PrintWriter.

Compile and test your program thoroughly.  Push your code to GitHub when your code is correct.


© 2024, Eric. All rights reserved.