所以我遇到了一些麻烦。我似乎无法弄清楚分配随机颜色的问题(请参阅注释掉的部分)。还有关于如何在正确回答时从上一个问题中删除文本的任何建议?任何帮助将不胜感激。
游戏驱动程序类
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);
}
}
}
}
您需要将该循环放在方法或构造函数中。像这样:
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));