对于我的java类,我们将要求用户输入,因此我决定创建一个仅返回整数值的方法。当我运行main并输入double时,它将返回0,并且不会返回try块来从用户那里获取另一个值。是不是应该在捕获到异常后返回try块?
import java.util.Scanner;
import java.util.InputMismatchException;
class MyMethods {
public static int getInteger() {
Scanner keyboard = new Scanner(System.in);
int integer = 1;
try {
System.out.println("Please enter integer");
integer = keyboard.nextInt();
}
catch(InputMismatchException e ) { //if anything besides an integer is entered we will catch here and go back to try block.
System.out.println("Please enter integer only!");
}
return integer;
}
}//end class
下面是测试
class methodTest {
public static void main(String[] args) {
int integerTest = MyMethods.getInteger();
System.out.println(integerTest);//prints 0 if double is entered
}//end main
}//end class
最佳答案
这里的一种选择是使用循环来不断提示用户输入,直到收到有效值为止:
public int getInteger() {
Scanner keyboard = new Scanner(System.in);
Integer value = null;
while (value == null) {
try {
System.out.println("Please enter integer");
value = keyboard.nextInt();
}
catch (InputMismatchException e) {
System.out.println("Please enter integer only!");
}
}
return value;
}
关于java - 如何使我的catch块回到方法中的try块?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52324107/