所以我遇到了一些麻烦。我似乎无法弄清楚我的问题是分配我的随机颜色(参见注释掉的部分)。还有任何建议,如何正确回答上一个问题的文本?任何帮助将不胜感激。
游戏驱动程序类
public class MemoryGame {
public static void main(String[] args) {
Questions q = new Questions();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Questions{
Random r = new Random();
private JFrame mainwindow;
private JLabel label1;
private JTextField txtQ1;
int num = 1;
String[] solution = new String[5];
String[] colors = {"red","green","blue","yellow","brown","black","purple","white","orange","grey"};
//for (int i = 0; i < solution.length; i++)
// {
// solution[i] = colors[r.nextInt(10)];
//}
public Questions()
{
JOptionPane.showMessageDialog(null,"How good is your memory?\nTry to memorize this color sequence:\n"+solution);
createContents();
mainwindow.setVisible(true);
}
private void createContents()
{
mainwindow = new JFrame();
mainwindow.setSize(600, 400);
mainwindow.setTitle("Memory Game");
mainwindow.setDefaultCloseOperation(mainwindow.EXIT_ON_CLOSE);
mainwindow.setLayout(new FlowLayout());
label1 = new JLabel();
txtQ1 = new JTextField(15);
label1.setText("Enter color number: "+num);
//Add Action to text box
txtQ1.addActionListener(new QuestionListener());
mainwindow.add(label1);
mainwindow.add(txtQ1);
}
public class QuestionListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
String guess = "";
guess = txtQ1.getText();
if (colors[num-1].equalsIgnoreCase(guess))
{
System.out.println("Congratulations continue to next question.");
num++;
label1.setText("Enter color number: "+num);
}
else
{
System.out.println("Sorry wrong color.");
}
if (num == 6)
{
label1.setText("Congratulations, Your memory is perfect");
txtQ1.setVisible(false);
}
}
}
}
答案 0 :(得分:3)
您需要将该循环放在方法或构造函数中。类似的东西:
public Questions()
{
for (int i = 0; i < solution.length; i++)
{
solution[i] = colors[r.nextInt(10)];
}
JOptionPane.showMessageDialog(null,"How good is your memory?\nTry to memorize this color sequence:\n"+solution);
createContents();
mainwindow.setVisible(true);
}
您也可以使用
JOptionPane.showMessageDialog(null,"How good is your memory?\nTry to memorize this color sequence:\n" + Arrays.toString(solution));