Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Can I get an explanation for the purpose of the if(args.length!==1) and (new File (args[0])? 7. Complete the following java program which scans a file
Can I get an explanation for the purpose of the if(args.length!==1) and (new File (args[0])?
7. Complete the following java program which scans a file containing only numbers and white space, and prints out the average value of all the numbers in the file. For instance, given a file called test containing the numbers: 2.4 3.4 5.8 6.0 7-3 12.2 8, and given that your program is called by doing % Java Problem7 test at the command line, your program will produce the following output. The average value in file test is 5.225 Your program will check that the number of command line arguments is equal to 1, and will initialize a Scanner object (in an appropriate try-catch block) pointing to the file named on the command line. If any of these tests fail, your program will exit with an error message. You may assume that the file will contain at least one number // Problem7.java import java.util.Scanner; import java.io.*; class Problem7 f public static void main (String[] args) ( //your begins here Scanner sc null; double sum; int count = 1; if(args.length!-1) [ System.out.println("Usage: java Problem7 filename"); System.exit(1); tryf sc - new Scanner (new File (args [0])); catch (FileNotFoundException e) System.err.println (e.getMessage )); System.exit(1); sum - sc.nextDouble (); while (sc.hasNextDouble ()) sum +- sc.nextDouble (); count+ System.out.println( "The average value in file " + args [0]+ "is "+ sum/count SC.Close // your code ends here
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started