java - 循环时出现 ArrayIndexOutOfBoundsException

标签 java

我对编程几乎是个菜鸟,但我已经研究了很多地方,但找不到答案。我使用 Eclipse,每次运行程序时都会显示:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at computer.guess(game1player2.java:24)
    at game1player2.main(game1player2.java:39)

这是我的代码:

import java.util.Scanner;

class computer{

    int g = 0;
    int[] compguess = new int[g];


    void guess(){

        int rand;
        while(0 < 1){

            int i;
            rand = (int) Math.ceil(Math.random()*10);
            for (i = 1; i < compguess.length; i++){

                if(rand == compguess[i]){
                    break;
                }
            }
            if(i > compguess.length){
                g++;
                rand = compguess[g];
                System.out.println(compguess[compguess.length]);
            }
        }
    }
}

public class game1player2 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        computer computer1 = new computer();
        for(int a = 0; a < 2; a++){
            computer1.guess();
            for(int n = 0; n <= computer1.compguess.length; n++)
                System.out.println(computer1.compguess[n]);
            }
    {
        input.close();
    }
    }
}

我现在真的很困惑,我试图让计算机生成一个随机数 1-10,但如果它已经在数组中,则会生成另一个随机数。

最佳答案

int g = 0;
int[] compguess = new int[g];

您的数组大小为 0,因此您没有有效的条目。

关于java - 循环时出现 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19412750/

相关文章:

java - 过滤查询以获取包含常量后跟特殊字符的字符串?

java - JFrame 窗口不显示任何内容,除非调整大小

java - 最后总是在方法完成之前执行?

java - 如何使用 java/kotlin 中的注释处理将方法附加到现有类?

java - 调整缓冲图像大小 - 按 2 的倍数调整大小

Java:用 ASCII 0 (NULL) 将字符串填充为 16 字节的倍数

java - 单击同一按钮上的Java Thread Start-Stop-Start

java - 是否可以在jtable中编辑数据并保存?

java - 加载 Java VM 时出现 Windows 错误 2

java - 如何使用 Pelops 客户端让每个节点与 Cassandra 数据库有 40 个连接?