我是编程新手,我们的老师要求我们编写一个程序,该程序可以使用数组猜测用户所想的数字。我这样做了:
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).
我已尝试调试它,但我仍在学习如何调试,但找不到错误。有人可以帮我确定错误在哪里以及如何解决吗?非常感谢!
最佳答案
你的内部 for 循环的条件应该是
for (int j = 0; j < 100; j++){
(条件是j < 100,不是i < 100)
关于java - 用java(数组)猜用户想过的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33279462/