JOptionPane中的猜数游戏,JPanel没有出现(Java)

时间:2015-12-08 05:51:01

标签: java swing joptionpane

所以我使用 JOptionPane 做了一个数字猜谜游戏程序,我的问题是,当我运行程序时,没有窗口显示,即使没有窗口,程序也会结束构建它时出错。

到目前为止我的代码就是这个。

import javax.swing.*;
import java.awt.*;
import java.util.*;

public class TestNo4 {
    public static void main(String[] args) {
        Random ranNum = new Random();
        int secretNum = ranNum.nextInt(100) + 1;
        int guess = 0;
        int guessNo = 0;
        int guessLimit = 5;

        JTextField numUserIn = new JTextField(5);
        JPanel getInput = new JPanel();
        getInput.add(new JLabel("Enter you guess(Limit of 5 guesses)"));
        getInput.add(numUserIn);

        for (int countGuess = 0; countGuess == guessLimit; countGuess++) {
            int numInput = JOptionPane.showConfirmDialog(null, getInput,
                    "Guess number " + countGuess, JOptionPane.OK_CANCEL_OPTION);
            if (numInput == JOptionPane.OK_OPTION) {
                guess = Integer.parseInt(numUserIn.getText());
                if (guess == secretNum) {
                    JOptionPane.showMessageDialog(null, "Congratulations!!",
                            "Got it in " + countGuess + " tries",
                            JOptionPane.INFORMATION_MESSAGE);
                    break;
                }
                if (countGuess == guessLimit) {
                    JOptionPane.showMessageDialog(null,
                            "Sorry, No more guesses left.", "The number is"
                                    + secretNum,
                            JOptionPane.INFORMATION_MESSAGE);
                    break;
                }
                if (guess > secretNum) {
                    JOptionPane.showMessageDialog(null, "Hint",
                            "Try something lower.",
                            JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "Hint",
                            "Try something higher.",
                            JOptionPane.INFORMATION_MESSAGE);
                }

            }
        }

    }
}

我出错的任何想法?

1 个答案:

答案 0 :(得分:1)

更改以下行并可以使用

for (int countGuess = 0; countGuess == guessLimit; countGuess++) {

for (int countGuess = 0; countGuess <= guessLimit; countGuess++) {

问题在于终止条件。因为它只检查相等的值,所以它永远不会运行循环。