【发布时间】:2015-10-22 11:02:20
【问题描述】:
我是编程新手,我们的老师要求我们编写一个程序,可以猜测用户使用数组想到的数字。我这样做了:
import java.util.Scanner;
public class Exercise11 {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Think a number between 1 and 100");
int array[] = new int[100];
for (int x = 0; x < 100; x++) {
array[x] = (int) ((Math.random() * 100) + 1);
}
//This allow us to fill the array with random numbers, without caring if they are repeated or not.
for (int i = 0; i < 100; i++) {
for (int j = 0; i < 100; j++) {
while (true) {
if (i != j && array[i] == array[j]) {
array[j] = (int) ((Math.random() * 100) + 1);
} else
break;
}
//If a number is repeated, this will swap that number with another number.
}
}
//Now we have filled the array. We ask the user:
for (int y = 0; y < 100; y++) {
System.out.println("¿Is it your number " + array[y] + "?");
String respuesta = entrada.next();
switch (respuesta) {
case "Yes":
System.out.println("I knew it! I only needed " + y + " trys!");
break;
case "No":
break;
}
}
}
}
但是当我执行它时它仍然会抛出错误,如下所示:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Ejercicio11.main(Ejercicio11.java:25).
我已经尝试调试它,但我仍在学习如何去做,我找不到错误。有人可以帮我确定错误在哪里,我该如何解决?非常感谢!
【问题讨论】:
-
如果您不知道解释此异常的提示:您遇到 ArrayIndexOutOfBoundsException - 这通常意味着您尝试在数组上使用不存在的索引(例如,您的数组为空并且您尝试使用第三个元素)。它还告诉你哪个方法抛出了它(这里是你的主要方法)以及发生错误的行号(这里是 25)
-
非常感谢,感谢您的提示。