Can I get an explanation for the purpose of the if(args.length!==1) and (new Fil
ID: 3733038 • Letter: C
Question
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 hereExplanation / Answer
java Problem7 test
In the above line we are giving the name of the input file( test ) to be read by the program as command line argument.
_______________
if(args.length!=1)
Here we are checking whether we passed any command line arguments or not.If the length is not equal to 1 means we didnt passed any filename as command line arguments.Then it will display the error message and the program will quit.
If not read the data from the input file named test and calculate the average .
___________________
String args[] ---This is the String array which holds command line arguments.
As we are passing only one input (file name called test) that will be stored in args[0]
___________________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.