What if I want to take user input from the args[0] array, but just in case I (the user) forgot to define it, I wanted a prompt to come up – is it better to use an if block to determine whether the array item(s) is empty or not, or to catch the exception? So, is this
public class Stuff {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String foo;
if(args.length > 0) {
foo = args[0];
}
else {
foo = getString("Input? ");
}
}
public static String getString(String prompt) {
System.out.print(prompt + " ");
String answer = input.nextLine();
return answer;
}
}
better or worse than
public class Stuff {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String foo;
try {
foo = args[0];
}
catch(ArrayIndexOutOfBoundsException e) {
foo = getString("Input? ");
}
}
public static String getString(String prompt) {
System.out.print(prompt + " ");
String answer = input.nextLine();
return answer;
}
}
You need to test
args.lengthrather than readingargs[0]But apart from that error, it is better to use
if/elsefor the following reasons: