简体   繁体   English

猜数字游戏

[英]Number guessing game

I have been trying to make a number guessing game. 我一直在尝试做一个猜数字游戏。 It has a set of numbers and it is supposed to count and display the number of times you have guessed once you guess the correct number. 它具有一组数字,并且一旦您猜对了正确的数字,就应该计算并显示您所猜测的次数。

Currently the program runs the first 2 steps then just stops please help to solve this 目前程序运行前2个步骤,然后停止,请帮助解决此问题

import javax.swing.JOptionPane;  
import java.util.Scanner;
//Scott Timmerman TwentyQuestions

public class TwentyQuestions {

    public static void main(String[] args) {
        int number = 500000;
        int numberoftries = 0; 
        JOptionPane.showMessageDialog(null, "Scott Timmerman TwentyQuestions");
        Scanner input = new Scanner(System.in);
        int guess;
        boolean win = false;
        while (win == false) {

            JOptionPane.showInputDialog("Enter a number between 1 and 1,000,000" );
            guess = input.nextInt(); 
            numberoftries++; 
            if(guess == number) {
                win = true;
            }
            else if(guess > number){
                JOptionPane.showMessageDialog(null, "your guess " + guess + " was greater then the number");

            }
            else if (guess < number){ 
                JOptionPane.showMessageDialog(null, "your guess " + guess + " was less then the number");

            }
        }

        JOptionPane.showMessageDialog(null, "you lost!\n the number was " + number );
        JOptionPane.showMessageDialog(null, "you won!" + numberoftries + " tries");

        }


}
    ` 

It looks as though you want the user to enter the next guess in the dialog box rather than at the console. 似乎您希望用户在对话框而不是控制台中输入下一个猜测。 If that's the case then you need to use the return value from JOptionPane.showInputDialog . 如果是这种情况,则需要使用JOptionPane.showInputDialog的返回值。 The return value is then the text that the user entered before clicking the ok button. 然后,返回值是用户在单击“ ok按钮之前输入的文本。 You will need to covert this to an integer using something like Integer.parseUnsignedInt which includes handling NumberFormatException (in case they type in something that isn't a number). 您将需要使用Integer.parseUnsignedInt东西将其隐瞒为整数,其中包括处理NumberFormatException (以防万一,他们键入的不是数字)。

So something like: 所以像这样:

try {
    String guessText = JOptionPane.showInputDialog("Enter your next guess");
    int guess = Integer.parseUnsignedInt(guessText);
} catch (NumberFormatException ex) {
    ...
}

It stops because the program wait till you provide the value on the console not on the Java Dialogue. 它停止了,因为程序等到您在控制台上而不是在Java Dialogue上提供值。 Switch to console and write there for example 500 and hit enter. 切换到控制台并在其中写入例如500,然后按Enter。 This is the problem: Scanner input = new Scanner(System.in); 这是问题所在:扫描仪输入=新的Scanner(System.in);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM