我该如何修复这个简单的程序?猜谜游戏

How do i fix this simple program? guessing game

你好,请,请,请有人帮助我。我正在编写一个程序,用户可以在其中输入猜谜游戏的最大数字,并且使用随机生成器 he/she 必须猜测从 1 到最大数字的数字。我已经完成了其中的大部分工作,但是如果用户说输入字母或除整数以外的任何其他内容,我仍然无法解决如何循环回程序以输入另一个输入的问题。 "do" 部分是我感到困惑的地方!

import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;

public class guessinggame { // class name

    public static void main(String[] args) { // main method

        String smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
        int max = Integer.parseInt(smax);
        do {
            if (max > 10000) {
                JOptionPane.showMessageDialog(null, "Oh no! keep your choice below 10000 please.");
                smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
                max = Integer.parseInt(smax);
            }
        } while (max > 10000);

        int answer, guess = 0, lowcount = 0, highcount = 0, game;
        String sguess;
        Random generator = new Random();
        answer = generator.nextInt(max) + 1;

        ArrayList<String> buttonChoices = new ArrayList<String>(); // list of string arrays called buttonChoices 
        buttonChoices.add("1-" + max + " Guessing Game");

        Object[] buttons = buttonChoices.toArray(); // turning the string arrays into objects called buttons

        game = JOptionPane.showOptionDialog(null, "Play or Quit?", "Guessing Game",
                JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE,
                null, buttons, buttonChoices.get(0));

        do {
            sguess = JOptionPane.showInputDialog("I am thinking of a number between 1 and " + max + ". Have a guess:");
            try {
                guess = Integer.parseInt(sguess);
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(null, "That was not a number! ");

            }

            if (guess < answer) {
                JOptionPane.showMessageDialog(null, "That is too LOW!");
                lowcount++;

            } else {
                JOptionPane.showMessageDialog(null, "That is too HIGH!");
                highcount++;
            }
            break;

        } while (guess != answer);
        JOptionPane.showMessageDialog(null, "Well Done!" + "\n---------------" + "\nThe answer was " + answer + "\nLow Guesses: " + lowcount
                + "\nHigh Guesses: " + highcount + "\n\nOverall you guessed: " + (lowcount + highcount) + " Times");

        System.exit(0);
    }
}

先到先得,break在最后do-while。如果你 break 在循环内没有条件;这不是循环;它是一个单执行块。

除此之外,在验证输入的区域中,您应该遵循此结构。 (伪代码,以便您可以实现)。

Do-While input does not equal answer
    Get input from user with dialogue

    Begin Try
        Parse user input
        If input > answer
           Notify user
        Else-If input < answer
           Notify user
    End Try
    Begin Catch Parse error
        Alert user of invalid input
    End Catch
End While