为什么我的第一个方法“ inputNumber”返回无限输出“这不是有效数字” 而第二种方法返回到“输入有效数字:”
我不明白为什么带有parseInt的方法不会做同样的事情... 他们都抛出异常并执行“捕获”。
这是我的代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("you typed the number: " + inputNumber(input));
}
public static int inputNumber(Scanner input) {
int num = 0;
while (num == 0) {
System.out.print("Type a number: ");
try {
return input.nextInt();
} catch (Exception e) {
System.out.println("this is not a valid number");
}
}
return num;
}
public int readNumber(Scanner input) {
boolean running = true;
while (running) {
System.out.print("Write a number: ");
try {
int num = Integer.parseInt(input.nextLine());
return num;
} catch (Exception e) {
System.out.println("this is not a valid number");
}
}
return 0;
}
}