Please write comments and explaining the code. This code should be very basic be
ID: 3775205 • Letter: P
Question
Please write comments and explaining the code. This code should be very basic becuase this is a low level java course, so you are limited to methodes, if-else statements, for and while loops, try and catch statements, arrays, expections, and fileI/O.
Write a program that reads a stream of integers from a file and prints to the screen the range of integers in the file (i.e. [lowest, highest]). You should first prompt the user to provide the file name. You should then read all the integers from the file, keeping track of the lowest and highest values seen in the entire file, and only print out the range of values after the entire file has been read.
Importantly, unlike the previous problem, you can make no assumptions about the contents of the file. If your program cannot read the file, opens an empty file, or encounters a non-integer while reading the file, your program should output that the file is invalid.
Test for several invalid files (e.g. non-existent, empty, non-integer) as well as files that contain only integer values.
"Use this example code as something to base off of(to get an idea of what i want).
Write a program that opens a file named integers.txt, then reads 5 integers from the file and prints each one out. You will have to create the integers.txt file manually first and put at least 5 integers into it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClassExamples {
public static void main(String[] args) {
try (Scanner fin = new Scanner(new File("integers.txt"))) {
for (int i = 1; i <= 5; i++) {
int nextInt = fin.nextInt();
System.out.println(nextInt);
}
}
catch (FileNotFoundException ex) {
System.out.println("File integers.txt not found!");
System.exit(0);
}
}
}
Explanation / Answer
HI, Please find my implementation.
Please let me know in case of any issue.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClassExamples {
public static void main(String[] args) {
int max = 0, min = 0;
try (Scanner fin = new Scanner(new File("integers.txt"))) {
for (int i = 1; i <= 5; i++) {
int nextInt = fin.nextInt();
if(i == 1){ // read first integer from file, so initialize min and max
min = nextInt;
max = nextInt;
}else{
if(min > nextInt)
min = nextInt;
if(max < nextInt)
max = nextInt;
}
System.out.print(nextInt+" ");
}
System.out.println();
System.out.println("Range: [ "+min+", "+max+" ]");
}
catch (FileNotFoundException ex) {
System.out.println("File integers.txt not found!");
System.exit(0);
}
}
}
/*
Sample run:
1 5 2 7 8
Range: [ 1, 8 ]
*/