簡體   English   中英

猜數字游戲

[英]Number guessing game

我一直在嘗試做一個猜數字游戲。 它具有一組數字,並且一旦您猜對了正確的數字,就應該計算並顯示您所猜測的次數。

目前程序運行前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");

        }


}
    ` 

似乎您希望用戶在對話框而不是控制台中輸入下一個猜測。 如果是這種情況,則需要使用JOptionPane.showInputDialog的返回值。 然后,返回值是用戶在單擊“ ok按鈕之前輸入的文本。 您將需要使用Integer.parseUnsignedInt東西將其隱瞞為整數,其中包括處理NumberFormatException (以防萬一,他們鍵入的不是數字)。

所以像這樣:

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

它停止了,因為程序等到您在控制台上而不是在Java Dialogue上提供值。 切換到控制台並在其中寫入例如500,然后按Enter。 這是問題所在:掃描儀輸入=新的Scanner(System.in);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM