Java coding. Write a program that reads a stream of integers from a file and pri
ID: 3764236 • Letter: J
Question
Java coding.
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. You have been supplied JUnit tests for several invalid files (e.g. non-existent, empty, non-integer) as well as files that contain only integer values.
Explanation / Answer
Here is the code.
import java.util.*;
import java.io.*;
public class ReadIntegers{
public static void main(String[] args) {
try
{
int temp, min, max;
System.out.println();
Scanner scanner = new Scanner(System.in);
String filename;
ArrayList<Integer> ints=new ArrayList<Integer>() ;
System.out.println("Please Enter the file name to read data from ");
filename = scanner.next();
//System.out.println("You Entered "+filename);
File fil = new File(filename);
if(!fil.exists() || fil.length()==0)
{
System.out.println("File either empty or not available");
return;
}
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
String s =in.readLine();
while(s!=null)
{
int i = 0;
ints.add(Integer.parseInt(s)); //this is line 19
//System.out.println(ints[i++]);
s = in.readLine();
}
in.close();
Integer vals[]=new Integer[ints.size()];
ints.toArray(vals);
min=vals[0]; max=vals[0];
for(int i=0;i<vals.length;i++)
{
if(vals[i]<min)
{
min=vals[i];
}
if(vals[i]>max)
{
max=vals[i];
}
}
System.out.println("Range is ["+min+", "+max+"]");
for(int i=0;i<vals.length;i++)
{
}
}
catch(NumberFormatException e)
{
System.out.println("Non Integer value encountered");
}
catch(FileNotFoundException e)
{
System.out.println("Invalid File");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.