我有这种方法,它工作正常。我需要放一个try/catch语句,所以如果用户输入一个字母,该方法可以继续执行 。我不知道在哪里发表声明,似乎无处不在我把它弄错了。请有人告诉我在哪里发表这个声明?while循环中的Java try-catch语句
public void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
number = in.nextInt();
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}
if (!end) {
System.out.println("I cant find number " + number
+ " in the array, please try again ");
}
}
}
你是什么意思“它得到错误”?只是添加'尝试{你的代码的一些部分}'不会帮助;因为你必须考虑当用户提供的输入不是数字时会发生什么。 – GhostCat
它循环并打印,直到达到stackoverflow –
如果用户输入不是数字,我该如何解决这个问题? –