throws FileNotFoundException. try/catch. n OUTPUT SAMPLE #1 for input.txt 1 OUTP
ID: 3849310 • Letter: T
Question
throws FileNotFoundException. try/catch. n OUTPUT SAMPLE #1 for input.txt 1 OUTPUT SAMPLE #1 for input.txt 3 4 5 6 x x x 8 12 x x 34 x x 10 3 4 5 6 xx x 8 12 x x 34 x x 10 20 20 Number 1 is 1 Please input the name of the file Number 2 is: 2 to be opened input. tx Number 3 is 3 File Not Found Number 4 is 4 OUTPUT SAMPLE #2 for input.txt 1. Number 5 is: 5 2 3 4 5 6 x x x 8 12 x x 34 x x 10 Number 6 is: 6 20 Number 7 is: Please input the name of the file Number 8 is 12 to be opened input.txt Number 9 is 34 Number 1 is 1 Number 10 is: 10 Number 2 is 2 Number 11 is 20 Number 3 is: 3 The average of 11 numbers/file Number 4 is: 4 9.55 Number 5 is: 5 Number 6 is 6 OUTPUT SAMPLE #2 for input.txt xxxxx x x x x xx Number 7 is Number 8 is 12 X X X X X The file doesn't contain any Number 9 is 34 integers. Exit program Number 10 is: 10 Number 11 is 20 The average of 11 numbers/file 9.55 OUTPUT SAMPLE #3 for input.txt xxxxx x x x x xx X X X X X Please input the name of the file to be opened input.txt The file doesn't contain any integers Exit programExplanation / Answer
import java.io.File;
import java.io.IOException;
import java.io.ClassNotFoundException;
public class Average
{
public static void main (String args[]) throws IOException, ClassNotFoundException
{
File infile = new File(" input.txt");
FileReader ins=null;
int sum =0;
int count =0;
int ch;
try {
while (( ch = ins.read())! = -1)
{
for (int i=0; i< ins.length;i++)
{ System.out.println(" Number #" +i "is:" (int)ch);
sum+=Interger.valueOf(ins.trim());
count++;
}
System.out.println("The average of" +count "numbers/file="+((double)sum/count));
}
catch (IOException ioe)
{ System.out.print(ioe);
System.out.print("The file doesn't contain any intergers. Exit program!");
System.exit(-1);
}
catch (ClassNotFoundException cnf)
{ System.out.print(" Please input the file name to be open");
}
}
}
here what I m doing is reading data with FileReader and displaying it on console. Please note that input.txt file already exists in your computer. Then I took sum and count variables where I directly get the sum of all the integers and as well as count the number of integers. I use trim() method to trim the space in between the variables. Then I calculate the average by simply dividing sum by count and displaying the same by converting it into double from integer. I m using try and catch blocks to catch the CNF and IO exceptions and exiting my program if the input file does not contain any integer value.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.