如果我想从args[0]
数组中获取用户输入,但万一我(用户)忘记定义它,我想要一个提示出现 - 使用if
块来确定数组项是否更好?是否为空,或捕获异常?那么,这是
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;
}
}
好于或差于
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;
}
}