首页 > 解决方案 > 循环和 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);
    }

}

}

标签: javaloopsjoptionpane

解决方案


您可以通过将所有内容无限地包装在 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

}

}

推荐阅读