java - 随机颜色游戏、数组和输入

标签 java

所以我遇到了一些麻烦。我似乎无法弄清楚分配随机颜色的问题(请参阅注释掉的部分)。还有关于在正确回答后如何从上一个问题中删除文本的任何建议?任何帮助将不胜感激。

游戏驱动类

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));

关于java - 随机颜色游戏、数组和输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29787719/

相关文章:

java - 亚马逊 AWS RAID 配置

java - 不让 AdMob 广告请求焦点?

java - jaas.conf 中未选取 KafkaClient 部分

java - 我在这个解析中做错了什么?

java - 当我调用 Jenkins json api 时,如何判断构建是否正在进行?

java - 使用 Map 值处理 Map

java - 仅在多项目构建中为相互依赖的项目编译 java 类

java - 如何从 php 文件获取变量并在 Android Activity 中使用它?

java - 选择抽屉项目后滚动到新选项卡

java - 按 Ctrl+A 正在更改 JTextPane 中的字体