簡體   English   中英

JOptionPane中的數字猜測游戲,JPanel未顯示(Java)

[英]Number guessing game in JOptionPane, JPanel is not showing up(Java)

因此,我使用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);
                }

            }
        }

    }
}

有什么想法我做錯了嗎?

更改以下行即可

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

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

問題在於終止條件。 由於它僅檢查相等的值,因此從不運行循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM