gpt4 book ai didi

java - 我的2D数组Java代码找不到错误

转载 作者:行者123 更新时间:2023-12-03 08:53:23 26 4
gpt4 key购买 nike

Java说存在预期的“]”错误。我找不到我的代码有什么问题吗? Song类是另一个类组合类,因此没有问题。在此先感谢您的帮助

public class Jukebox
{
Song[][] songList;

songList[0][0] = new Song("Jet Airliner", 5 );

songList[0][1] = new Song( "Slide", 4 );

songList[0][2] = new Song( "Tom Sawyer", 3 );
songList[0][3] = new Song( "Purple Rain", 2 );
songList[1][0] = new Song( "Sing a Song", 1 );
songList[1][1] = new Song( "Baba O'Riley", 5 );
songList[1][2] = new Song( "Jumper", 4 );
songList[1][3] = new Song( "Car Wash", 3 );
songList[2][0] = new Song( "Kung Fu Fighting", 2 );
songList[2][1] = new Song( "Right as Rain", 4 );
songList[2][2] = new Song( "Beat It", 5 );
songList[2][3] = new Song( "Bust a Move", 4 );

public String toString()
{
String output = " ";
for (int row = 0; row < songList.length; row++)
{
for (int col = 0; col < songList[row].length; col++)
{
output+=(songList[row][col]);
}
output += "\n";
}
return output;
}

}

最佳答案

您需要在方法中执行以下所有操作:

songList[0][0] = new Song("Jet Airliner", 5 );

songList[0][1] = new Song( "Slide", 4 );

songList[0][2] = new Song( "Tom Sawyer", 3 );
songList[0][3] = new Song( "Purple Rain", 2 );
songList[1][0] = new Song( "Sing a Song", 1 );
songList[1][1] = new Song( "Baba O'Riley", 5 );
songList[1][2] = new Song( "Jumper", 4 );
songList[1][3] = new Song( "Car Wash", 3 );
songList[2][0] = new Song( "Kung Fu Fighting", 2 );
songList[2][1] = new Song( "Right as Rain", 4 );
songList[2][2] = new Song( "Beat It", 5 );
songList[2][3] = new Song( "Bust a Move", 4 );

因此,您可以创建一个 init()方法,或者根据需要创建一个构造函数。
public void init(){
songList = new String[3][4];
songList[0][0] = new Song("Jet Airliner", 5 );

songList[0][1] = new Song( "Slide", 4 );

songList[0][2] = new Song( "Tom Sawyer", 3 );
songList[0][3] = new Song( "Purple Rain", 2 );
songList[1][0] = new Song( "Sing a Song", 1 );
songList[1][1] = new Song( "Baba O'Riley", 5 );
songList[1][2] = new Song( "Jumper", 4 );
songList[1][3] = new Song( "Car Wash", 3 );
songList[2][0] = new Song( "Kung Fu Fighting", 2 );
songList[2][1] = new Song( "Right as Rain", 4 );
songList[2][2] = new Song( "Beat It", 5 );
songList[2][3] = new Song( "Bust a Move", 4 );
}

现在,在调用 toString()JukeBox方法之前,您需要先调用 init()方法。

关于java - 我的2D数组Java代码找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34782562/

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