JAVA Write a program that will search a text file of strings representing numbers of type int and will write the largest and the smallest numbers to the screen. Include appropriate error handling in case a line contains more than one int or it contains a String. Wrap all the work you are doing with the file in a try/catch/finally block with appropriate "catch" sections; the finally block will be where you close your file object (if desired, look this up online for more information regarding "finally" and when it is executed, specifically that it is executed in case of success or failure of the entire try block).
/*Java program that reads an input file, data.txt
file that contains data values. Then program read
* only valid data and then find the maximum and minimum values.The
program prints the invalid
* data to console.
* */
//MAXMIN.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MAXMIN
{
public static void main(String[] args)
{
//Set file name
String fileName="data.txt";
Scanner filereader=null;
int num;
int min;
int max;
try
{
filereader=new
Scanner(new File(fileName));
min=Integer.parseInt(filereader.nextLine());
//assume
starting value is max and min values
max=min;
/*Read file till
end of file */
while(filereader.hasNextLine())
{
String line=filereader.nextLine();
if(line.contains(" "))
System.out.println("Invalid
input : "+line);
else if(line.matches("^[A-Za-z]+$"))
System.out.println("Invalid
input : "+line);
else
{
num=Integer.parseInt(line);
if(num<min)
min=num;
if(num>max)
max=num;
}
}
//prinnt
maximum and minimum values
System.out.println("***MAX and MIN values***");
System.out.println("Maximum value : "+max);
System.out.println("Minimum value : "+min);
}
//catch exceptioin if file not
found
catch(FileNotFoundException
exp)
{
System.out.println(exp.getMessage());
}
//close the file in finally
block
finally
{
filereader.close();
}
}//end of main method
} //end of the class
-------------------------------------------data.txt file
values---------------------------------------------------------------
5
6 7
one
1
5
10
99
0
------------------------------------------Sample Output#--------------------------------------------------------
Get Answers For Free
Most questions answered within 1 hours.