In: Computer Science
QUESTION:
Add code so that if no parameter values are specified for method “main”, then the error message “file name expected” is printed out instead of the "Opening file " message. Hint: If no parameter values are specified for method “main”, then the length of the array “args” will be zero. If that error message “file name expected” is printed out, the program should stop. You can make any Java program stop using this line …
System.exit(0);
skeleton code:
/**
* This is a simple program for the first lab, to familiarise
students
* with the lab and with plate.
*
* @author Raymond Lister
* @version March 2015
*/
public class Assignment
{
public static void main(String[] args)
{
// DO NOT CHANGE THIS LINE OR ANYTHING ABOVE THIS LINE
String[] list = {"Hello.txt"};
System.out.println("Opening file "+ list[0]);
// DO NOT CHANGE THIS LINE OR ANYTHING BELOW THIS LINE
}
}
Source Code :
//assignment class
public class Assignment
{
//main function
public static void main(String[] args)
{
// DO NOT CHANGE THIS LINE OR ANYTHING
ABOVE THIS LINE
String[] list = {"Hello.txt"};
//check main function has a parameter or not
//args array hold the arguments passed to main function
//if no arguments are passed the size of args array is 0
if(args.length==0){
//if arguments are not passed
//print the error message
// "file name expected"
System.out.println("file name expected ");
//after priting the error message
//stop the program
System.exit(0);
}
//if arguments are passed to main function
//print opening file
System.out.println("Opening file "+ list[0]);
// DO NOT CHANGE THIS LINE OR ANYTHING
BELOW THIS LINE
}
}
Output and screenshots :