In: Computer Science
Write a program to perform the following actions: the language is Java
– Open an output file named “Assign14Numbers.txt”
– Using a do-while loop, prompt the user for and input a count of the number of random integers to produce, make sure the value is between 35 and 150, inclusive.
– After obtaining a good count, use a for-loop to generate the random integers in the range 0 ... 99, inclusive, and output each to the file as it is generated with one integer per line (no extra spaces, tabs, or lines).
– Close output file – open and view it in the IDE editor if desired.
– In program, add code to reopen the same file for input.
– Using an EOF while-loop to detect the end of data, input and display all data items from the file formatted as stated in the next instruction – do NOT use a counting loop to input the data!
– Display the random integers from the file to the console with 15 numbers per line formatted with right-alignment in columns that are exactly 4 positions wide, there must be exactly 1 blank line above and below the numbers displayed on the console.
– Close the input file.
Complete code in java:-
import java.util.*;
import java.io.*;
class random {
public static void main(String ... args) {
// Creating scanner object to take
input from an input stream.
Scanner sc = new
Scanner(System.in);
// Creating Random object to
generate random numbers.
Random rand = new Random();
int count;
// Opening file to write
into.
try {
FileWriter fw =
new FileWriter("Assign14Numbers.txt");
// Taking number
of numbers that will be printed intot he opened file.
do {
System.out.print("Enter a number in range 35-150
(inclusive) : ");
count = sc.nextInt();
}while(count
< 35 || count > 150);
// Generating
random numbers and writting them into file.
for(int i = 0; i
< count; i++) {
int num = rand.nextInt(100);
fw.write(num+"\n");
}
// Closing
file.
fw.close();
} catch (IOException e) {
System.out.println("IO Error has occured, try again...");
}
// Again opening file into read
mode, to read from
try {
// Creating
Input stream object for file.
FileInputStream
fr = new FileInputStream("Assign14Numbers.txt");
// Creating
scanner object to read from file stream stream
sc = new
Scanner(fr);
// Count will
keep track the number of numbers to be printed in a line, specified
15.
count = 0;
// Printing
formatted data.
System.out.println();
String output =
"";
// Readin from
file until end of file (EOF).
while(sc.hasNextLine()) {
if(count == 15) {
System.out.printf("%s\n",
output);
output = "";
count = 0;
}
// I am using tab "\t" to make columns 4
position wide,
// because "\t" is equal to 4 spaces.
output += ("\t"+sc.nextLine());
count++;
}
System.out.printf("%s\n\n", output);
sc.close();
} catch (IOException e) {
System.out.println("IO Error has occured try again...");
}
}
}
Screenshot of output:-