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;
}
}
Your first example will still throw an exception since in the if statement you are still accessing an index which does not exist.
If you want to use an if statement then you should be checking that the length of the array is greater than the index you are trying to access for example:
if(args.length > 0)
foo = args[0];
You need to test args.length rather than reading args[0]
But apart from that error, it is better to use if/else for the following reasons:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With