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

Hello everyone! I am very confused with how to do this programming assignment fo

ID: 3777916 • Letter: H

Question

Hello everyone! I am very confused with how to do this programming assignment for computer science. If anyone can help me I would greatly appreciate it! The assignment is described below: "Write a Java 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, 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." Thank you very much in advance everyone!

Explanation / Answer


// MinMax.java

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

public class MinMax
{

   public static void main(String args[]) throws IOException
   {
      Scanner sc=new Scanner(System.in);

      System.out.println("Enter filename: ");
      String fileName=sc.next();

       ArrayList<Integer> numbers = new ArrayList<Integer>(25);
       Scanner filescasnner = null;
     
     
       try
       {
           filescasnner=new Scanner(new File(fileName));
           int highest = Integer.MIN_VALUE;
           int lowest = Integer.MAX_VALUE;

           while(filescasnner.hasNextInt())
           {
               int number = filescasnner.nextInt();

               numbers.add(number);

               if(number > highest)
                  highest = number;
               if(number < lowest)
                  lowest = number;

           }

           Collections.sort(numbers);

           System.out.println(" Numbers in file from lowest to highest: ");
           for (Integer number: numbers)
           {
               System.out.print(number+ " ");
           }
           System.out.println(" Lowest: " + lowest);
           System.out.println("Highest: " + highest);

           filescasnner.close();
       }
     
    
       catch (FileNotFoundException e)
       {
           System.out.println("File is invalid! Cannot open file");
       }

    
   }
}

/*
input.txt
4 9 2 3 5 7 8 1 6


output:
Enter filename: input.txt

Numbers in file from lowest to highest:
1 2 3 4 5 6 7 8 9
Lowest: 1
Highest: 9

*/

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