为什么默认数组构造在此设置中不起作用?这些是我得到的错误:
"]"预期, &#34 ;;"预期, 非法开始类型,预期标识符(每次8次)
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
class ButtonHandler implements ActionListener {
ColoredWordsExperiment coloredWords;
public ButtonHandler(ColoredWordsExperiment coloredWords) {
this.coloredWords = coloredWords;
}
String colorWords[] = new String[8];
colorWords[0] = "blue";
colorWords[1] = "red";
colorWords[2] = "purple";
colorWords[3] = "yellow";
colorWords[4] = "green";
colorWords[5] = "pink";
colorWords[6] = "orange";
colorWords[7] = "grey";
@Override
public void actionPerformed(ActionEvent e){
//If button "Matching" is clicked
if (e.getActionCommand().equals("Matching")) {
coloredWords.label1.setText(colorWordGenerator(colorWords));
}
}
public String colorWordGenerator(String colorWords[]) {
Random generator = new Random();
int i = generator.nextInt(7);
return colorWords[i];
}
}
但是,如果我将数组放在一个像这样的新的干净的类中,它确实有效。
public class {
public static void main(String[] arg) {
String colorWords[] = new String[8];
colorWords[0] = "blue";
colorWords[1] = "red";
colorWords[2] = "purple";
colorWords[3] = "yellow";
colorWords[4] = "green";
colorWords[5] = "pink";
colorWords[6] = "orange";
colorWords[7] = "grey";
}
}
答案 0 :(得分:1)
类主体包含方法和变量定义。变量定义可能带有初始化程序。但是,您无法将任意语句放入类主体中。换句话说,您不能将赋值语句放入类主体中 - 您需要将它们放入方法或构造函数中。
在你的第二段代码中,分配都在一个方法中,所以那个编译好的原因。
在这种特殊情况下,比将赋值语句放入构造函数更好的解决方案是,根本不分配给数组的各个索引,而是使用大括号用这样的值初始化数组:
String colorWords[] = {"blue", ...};