We can catch this exception and ask the user to enter a different…
Question Answered step-by-step We can catch this exception and ask the user to enter a different… We can catch this exception and ask the user to enter a different file name. Here is a complete program that uses all these ideas: /** * This program reads numbers from a file. It computes the sum and * the average of the numbers that it reads. The file should contain * nothing but numbers of type double; if this is not the case, the * output will be the sum and average of however many numbers were * successfully read from the file. The name of the file will be * input by the user. */ public class ReadNumbersFromFile { public static void main(String[] args) { while (true) { String fileName; // The name of the file, to be input by the user. TextIO.put(“Enter the name of the file: “); fileName = TextIO.getln(); try { TextIO.readFile( fileName ); // Try to open the file for input. break; // If that succeeds, break out of the loop. } catch ( IllegalArgumentException e ) { TextIO.putln(“Can’t read from the file “” + fileName + “”.”); TextIO.putln(“Please try again.n”); } } // At this point, TextIO is reading from the file. double number; // A number read from the data file. double sum; // The sum of all the numbers read so far. int count; // The number of numbers that were read. sum = 0;count = 0; try { while (true) { // Loop ends when an exception occurs. number = TextIO.getDouble(); count++; // This is skipped when the exception occurs sum += number; } } catch ( IllegalArgumentException e ) { // We expect this to occur when the end-of-file is encountered. // We don’t consider this to be an error, so there is nothing to do // in this catch clause. Just proceed with the rest of the program. } // At this point, we’ve read the entire file. TextIO.putln(); TextIO.putln(“Number of data values read: ” + count); TextIO.putln(“The sum of the data values: ” + sum); if ( count == 0 ) TextIO.putln(“Can’t compute an average of 0 values.”); else TextIO.putln(“The average of the values: ” + (sum/count)); } } Image transcription textt startingVelue as the initial value of N. It also prints the number I of terms in the sequence. The value of theparameter. startingValue. t must he a positive integer. 1! static void print3NBequence{int startingValue) { int N; If?ne of the terms in the sequence. int count: I! The number of terms found. int onLine; If The numb… Show more… Show moreHighlight on the concept of opening a file and closing a file in C++. (10 Marks)Differentiate between functions and class templates. (10 Marks) Computer Science Engineering & Technology Software engineering Share QuestionEmailCopy link Comments (0)


