数字猜谜游戏

时间:2015-07-09 22:49:57

标签: java eclipse

我一直试图做一个数字猜谜游戏。它有一组数字,一旦你猜出正确的数字,它应该计算和显示你猜对的次数。

目前该程序运行前两个步骤然后停止请帮助解决此问题

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");

        }


}
    ` 

2 个答案:

答案 0 :(得分:1)

看起来您希望用户在对话框中而不是在控制台中输入下一个猜测。如果是这种情况,那么您需要使用JOptionPane.showInputDialog的返回值。然后返回值是用户在单击ok按钮之前输入的文本。您需要使用类似Integer.parseUnsignedInt的内容将其转换为整数,其中包括处理NumberFormatException(如果他们输入的数字不是数字)。

类似于:

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

答案 1 :(得分:0)

它会停止,因为程序会等到您在控制台上提供的值而不是Java Dialogue上的值。 切换到控制台并在那里写例如500并按Enter键。 这是问题:扫描仪输入=新扫描仪(System.in);