In: Computer Science
Java
Complete Example.java to fulfill the following problem statement:
Write a program to accept a list of numbers, one per line. Input is provided from a file if one is provided as the first command line argument. If a file is not provided, input should be read from the terminal.
The numbers can either be whole numbers or floating point numbers. The program should continue to accept input until a number equal to 00 is input. Of course, if the input in a file ends before a 00, that can be treated as the end of the input.
Once 00 is received or the input ends, the program should print the largest and smallest number provided as input (not including the 00 to end input). Sample outputs are shown below.
The program should catch and handle all common exceptions. When an exception is caught, the program should print the name of the exception, followed by the message included in the exception. It should then continue to accept input (if possible). Specifically, if it is unable to open the file provided, input should be read from the terminal.
Thanks!
I have implemented the MinMaxFinder to read input either from file or standard input and find Smallest,largest numbers per the given description.
Please find the following Code Screenshot, Output, and Code.
ANY CLARIFICATIONS REQUIRED LEAVE A COMMENT
1.CODE SCREENSHOT :
2.OUTPUT :
3.CODE :
import java.io.*;
public class MinMaxFinder
{
public static void main(String[] args)throws Exception
{
/*To Store smallest,largest and temp(t)*/
double smallest=0,largest=0,t=0;
//flag to check the file exits
//'i' to initilize the first smallest and largest
int i=0,flag=0;
//Create a BufferedReader class Object to read from standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//if the number of arguments is '1'
if(args.length==1){
//open the file
File file = new File("input.txt");
//if the file exists
if (file.exists()) {
//create a buffered reader object to the file
br = new BufferedReader(new FileReader(file));
flag=1;
}
}
//if flag=0 then we read data from input
if(flag==0){
System.out.println("Enter Numbers One per Line Ending with '00'");
}
String st;
//loop until 'EOF' or '00' is reached
while ((st = br.readLine()) != null &&!st.equals("00"))
try{
//Convert the number from string
t=Double.parseDouble(st);
//if the element is the fisrt element then it is both smallest and largest
if(i==0){
smallest=t;
largest=t;
i++;
}
//otherwise we compare with previous values
if(smallest>t)
smallest=t;
if(largest<t)
largest=t;
}catch(NumberFormatException e){
//if there is any exception we print the exception
System.out.println(e);
}
//print the result
System.out.println("The Smallest Number : "+smallest);
System.out.println("The Largest Number : "+largest);
}
}
input.txt:
1
29
38
34
35
23
4
3
2
1
-321
31
3
00