Java 尝试捕获扫描仪
我正在使用扫描仪获取用户输入。如果用户输入名称,我会将其添加到ArrayList中。如果用户没有输入名称,那么我想抛出一个异常,但我想继续得到答案的循环Java 尝试捕获扫描仪,java,exception,java.util.scanner,Java,Exception,Java.util.scanner,我正在使用扫描仪获取用户输入。如果用户输入名称,我会将其添加到ArrayList中。如果用户没有输入名称,那么我想抛出一个异常,但我想继续得到答案的循环 for(int i = 0; i < totalLanes; i++){ runArr.add(this.addRacer()); } public static String addRacer() throws NullPointerException{ System.out.print("Enter a name f
for(int i = 0; i < totalLanes; i++){
runArr.add(this.addRacer());
}
public static String addRacer() throws NullPointerException{
System.out.print("Enter a name for a racer: ");//Method uses try catch to catch a NullPointerException.
Scanner sc = new Scanner(System.in);
String rName = null;
try {
if(!sc.nextLine().isEmpty()){
rName = sc.nextLine();
}else{
throw new NullPointerException("name cannot be blank");
}
}
catch (NullPointerException e) {
System.out.println(e.toString());
System.out.print("Enter a name for a racer: ");
addRacer();
}
return rName;
}
为什么会无限重复?
从用户处检索输入的最佳方法是什么
确定他们输入的数据有效吗?
提前感谢。问题是您读取了两次输入。 我的意思是在代码中有两个sc.nextLine方法调用。 请尝试以下方法:
String rName = sc.nextLine();
try {
if(rName.isEmpty()){
throw new NullPointerException("Name cannot be blank.");
}
}
你不应该为此抛出一个例外。只需使用while循环:
String rName = sc.nextLine();
while (rName.isEmpty()) {
System.out.println("Name can't be blank. Try again.");
rName = sc.nextLine();
}
return rName;
在该循环之后,您的变量中保证有一个非空名称,并且您可以使用该名称添加一个新的racer。您不需要递归。您可以使用do{},而在您的情况下,这是一种更好的方法:
Scanner sc = new Scanner(System.in);
String rName;
do {
System.out.print("Enter a name for a racer: ");
rName = sc.nextLine();
try {
if (rName.isEmpty()) {
//throw and exception
throw new NullPointerException("name cannot be blank");
}
} catch (NullPointerException e) {
//print the exception
System.out.println(e.getMessage());
}
} while (rName.isEmpty());
return rName;
catch (NullPointerException e) {
System.out.println(e.toString());
System.out.print("Enter a name for a racer: ");//remove this
addRacer();//remove this
}
因此,只有在catch中的值不为空时,才能中断循环。不要调用catch中的addRacer函数。并删除我标记的行。对递归使用if-else条件
catch (NullPointerException e) {
System.out.println(e.toString());
System.out.print("Enter a name for a racer: ");//remove this
addRacer();//remove this
}
你的编程问题是什么?问题不清楚,如果addRacer不返回,这将无限期地重复出现。根据您的代码,如果if条件永远不满足,就会发生这种情况。。。。阅读下面@Grzegorz Górkiewicz的答案