我正在尝试创建一个双字符串。我认为这是分配价值的一种方式。我知道有更好的方法,但我老师建议这样做。但是,当我把它放进去时,每个人都会收到错误说明:
无法找到符号cellPhoneNumbers ']'预计
最终我要做的是创建一个看起来像这样的图表
智利 ******* 瑞典 * 秘鲁 ***************
public class GraphNumbers
{
String[][] cellPhoneNumbers = new String[5][1];
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
}
为什么我收到此消息?
答案 0 :(得分:3)
某些代码必须放在方法中,例如:
public class GraphNumbers
{
//changed the size of the array so you could do what you want
//you must have had a misscount when you originally made it
String[][] cellPhoneNumbers = new String[5][2];
//put in constructor or another appropriately named method
public GraphNumbers()
{
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
}
}
答案 1 :(得分:2)
根据Java语言语法,您不能在类中放置可执行语句。那些应放在方法/构造函数/代码块中。
所以你需要移动这些陈述:
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
到适当的地方,也许是在构造函数中。
此外,您的代码会在雄蕊中溢出数组,例如:
cellPhoneNumbers[0][1] = "21";
所以你需要第二个数组的大小为2而不是1.改变这个
String[][] cellPhoneNumbers = new String[5][1];
到
String[][] cellPhoneNumbers = new String[5][2];