循环和 showConfirmDialog

Loops and showConfirmDialog

我是 Java 的新手,我需要帮助。我创建了一个游戏,其中程序生成一个随机数 (1-100),用户必须猜测它。游戏有效。我遇到的问题是,当用户猜出正确的数字时,我必须使用 showConfirmDialog 询问播放器,如果他们想再次播放,然后使用循环来再次播放或完成。谁能告诉我该怎么做?任何事情都将不胜感激。

package guessinggame;

import javax.swing.JOptionPane;

public class Guessinggame {

public static void main(String[] args) {

    int guess;
    int numguess = 0;
    int usernum;

    int result = JOptionPane.showConfirmDialog(null, " Do you want to play? ", " Notice ", JOptionPane.YES_NO_OPTION);

    if (result == JOptionPane.YES_OPTION) {

        do {
            //game starts here
            guess = (int) (Math.random() * 100 + 1);
            usernum = Integer.parseInt(JOptionPane.showInputDialog("enter your guess"));
            numguess++;

            if (usernum > guess) {
                System.out.println(usernum + " is too high. Try again");
            } else if (usernum < guess) {
                System.out.println(usernum + " is too low. Try again");
            }
        } while (guess != usernum);

        int IQ = ((int) (Math.random() * 100 + 1)) + numguess;
        JOptionPane.showMessageDialog(null, " Correct, it took you " + numguess + " tries. Your IQ is " + IQ);

        //Use showConfirmDialog to if player wants to play again. 
        // If user chooses yes, play game again. If user chooses no end game
    } else if (result == JOptionPane.NO_OPTION) {
        JOptionPane.showMessageDialog(null, "Quiting? Bye!");
        System.exit(0);
    }

}

}

你可以像这样无限地将所有内容包装在一个 while 循环中:

package guessinggame;

import javax.swing.JOptionPane;

public class Guessinggame {

public static void main(String[] args) {

    int guess;
    int numguess = 0;
    int usernum;

  while(true) { //Start of while loop

    int result = JOptionPane.showConfirmDialog(null, " Do you want to play? ", " Notice ", JOptionPane.YES_NO_OPTION);

    if (result == JOptionPane.YES_OPTION) {

        do {
            //game starts here
            guess = (int) (Math.random() * 100 + 1);
            usernum = Integer.parseInt(JOptionPane.showInputDialog("enter your guess"));
            numguess++;

            if (usernum > guess) {
                System.out.println(usernum + " is too high. Try again");
            } else if (usernum < guess) {
                System.out.println(usernum + " is too low. Try again");
            }
        } while (guess != usernum);

        int IQ = ((int) (Math.random() * 100 + 1)) + numguess;
        JOptionPane.showMessageDialog(null, " Correct, it took you " + numguess + " tries. Your IQ is " + IQ);

        //Use showConfirmDialog to if player wants to play again. 
        // If user chooses yes, play game again. If user chooses no end game
    } else if (result == JOptionPane.NO_OPTION) {
        JOptionPane.showMessageDialog(null, "Quiting? Bye!");
        System.exit(0);
    }

  } //End of While Loop

}

}