Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads a stream of integers from a file and prints to the sc

ID: 3776571 • Letter: W

Question

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.

Explanation / Answer

ReadFileNumbers.java


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFileNumbers {

  
   public static void main(String[] args) throws FileNotFoundException {
       Scanner scan = new Scanner(System.in);
       System.out.print("Enter the file name: ");
       String fileName = scan.next();
       File file = new File(fileName);
       int max = Integer.MIN_VALUE;
       int min = Integer.MAX_VALUE;
       if(file.exists()){
           try{
           Scanner scan1 = new Scanner(file);
           if(scan1.hasNext()){
               while(scan1.hasNext()){
                   int n= scan1.nextInt();
                   if(min > n){
                       min = n;
                   }
                   if(max < n){
                       max = n;
                   }
               }
               System.out.println("highest number is "+max);
               System.out.println("lowest number is "+min);
           }
           else{
               System.out.println("File is an empty");
           }
           }
           catch(Exception e){
               System.out.println("File is invalid. File has a a non-integers.");
           }
       }
       else{
           System.out.println("File does not exist");
       }
   }

}

Output:

Enter the file name: D: umbers.txt
highest number is 9
lowest number is 1

numbers.txt

3
4
2
1
5
7
6
9
8

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote