java - 用java(数组)猜用户想过的数字

标签 java arrays for-loop

我是编程新手,我们的老师要求我们编写一个程序,该程序可以使用数组猜测用户所想的数字。我这样做了:

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/

相关文章:

java - spring集成测试事务不回滚

arrays - 圆形阵列切片

java - 将 byte[] 数组转换为 Unicode、UnicodeWithBOM 等

javascript - 使用 Javascript 创建表

excel - 需要添加粘贴特殊条件a copy.destination for 循环

java - 当 View 包含 ListView 时,Android OnGestureListener 问题

java - 如何使用 PEM 文件在 Java 中创建 SSL 套接字?

java - 找到数组中最小和最大的元素并打印元素的位置

java - 如何使for循环扫描器代码下降一定数量?

java - 推送通知不正确 - Android