如果我想从 args[0]
数组中获取用户输入,但以防万一我(用户)忘记定义它,我想要出现提示 - 是吗?最好使用 if block 来确定数组项是否为空,或者捕获异常?那么,是这样的
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;
}
}
最佳答案
您的第一个示例仍会引发异常,因为在 if 语句中您仍在访问不存在的索引。
如果您想使用 if 语句,那么您应该检查数组的长度是否大于您尝试访问的索引,例如:
if(args.length > 0)
foo = args[0];
关于java - Try...catch 与 if...else 的异常 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11259442/