有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

猜测用户对java的想法(数组)

我对编程有点陌生,我们的老师让我们制作一个程序,可以猜测用户使用数组时想到的数字。我这样做:

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).

我试过调试它,但我仍在学习如何去做,我找不到错误。有人能帮我确定错误在哪里以及如何修复它吗?非常感谢


共 (1) 个答案

  1. # 1 楼答案

    内部for循环的条件应为

    for (int j = 0; j < 100; j++){
    

    (条件是j<;100,而不是i<;100