【问题标题】:Guessing the number that the user has thought with java (arrays)用java(数组)猜测用户想到的数字
【发布时间】: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)
  • 非常感谢,感谢您的提示。

标签: java arrays for-loop


【解决方案1】:

你的内部 for 循环的条件应该是

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

(条件是j ,而不是i )

【讨论】:

  • 非常感谢!我没有意识到,我检查了四次!现在可以了,谢谢!编辑:我也意识到尝试次数应该是(y+1)。
猜你喜欢
  • 2022-11-24
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 2013-07-26
  • 2022-10-18
  • 2019-07-17
  • 2016-02-01
  • 1970-01-01
相关资源
最近更新 更多