gpt4 book ai didi

Java 2D 数组越界

转载 作者:行者123 更新时间:2023-12-01 10:50:05 25 4
gpt4 key购买 nike

请耐心听我说,这周我有医院预约,不幸的是我不知道如何使用二维数组,而大麦知道这方面的数组。不过我正在努力弄清楚它们。我正在运行下面的代码作为我的项目的测试,但收到以下错误

How many players? 2
What is your name: alan
What is your name: joseph
Exception in thread "main" 27
alan's Turn!
java.lang.ArrayIndexOutOfBoundsException: 0
at ASgn8.main(ASgn8.java:41)

我的代码如下

import java.util.Arrays;
import java.util.Scanner;

class ASgn8 {

public static void main(String[] args)
{

Die[][] myDie = new Die[0][0];

Scanner scan = new Scanner(System.in);

System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();

String[] playerNames = new String[playerCount];

for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
playerNames[i] = scan.nextLine();

}

int again = 1;

int randomNum = (int)(Math.random() * (30-10)) +10;
System.out.println(randomNum);


Die firstRoll = new Die();

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

System.out.println(playerNames[j] + "'s Turn! ");

firstRoll.roll();

myDie[j][0] = firstRoll;


}





}

}

当我单击错误时,它会突出显示以下内容

myDie[j][0] = firstRoll;

最佳答案

您的数组 Die[][] myDie = new Die[0][0]; 的大小为零乘零。任何访问它的尝试都将超出范围。

尝试将其初始化为一些非零维度,例如Die[][] myDie = new Die[10][10]; 将为您提供一个 10*10 二维数组。

关于Java 2D 数组越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33966671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com