[英]Java Guessing Game(Specifically JOptionPane)
所以我最近自學了一些JOptionPane。 我正在嘗試制作一個使用JOptionPane的Guessing游戲。 目前,這是我的代碼:
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.Random;
public class GuessingGameJOptionPane {
public static void main(String[] args) {
int guess, numberToGuess, numberOfTries = 0;
String input;
boolean win;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
numberToGuess = rand.nextInt(100);
JOptionPane.showInputDialog(null, null,"Please enter your name.", JOptionPane.QUESTION_MESSAGE);
win = false;
int guess1 = Integer.parseInt(JOptionPane.showInputDialog(null,null,"Guess a number between 1 and 1000", JOptionPane.QUESTION_MESSAGE));
while(win == false){
numberOfTries++;
if(numberToGuess < guess1)
{
JOptionPane.showMessageDialog(null,"The number you guessed was to low. Please try again" ,null , JOptionPane.INFORMATION_MESSAGE);
}
else if(numberToGuess > guess1){
JOptionPane.showMessageDialog(null,"The number you guessed was to high. Please try again" ,null , JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "Congratulations you won. The number was " + numberToGuess + ". It took you " + numberOfTries, null, JOptionPane.INFORMATION_MESSAGE);
win = true;
}
}//Win == False
}//Main Method
}//類
輸入數字后,它會連續說出您的數字是低還是高,並繼續創建新的窗格。 任何幫助將不勝感激謝謝。
您的問題特別存在於這里:
int guess1 = Integer.parseInt(JOptionPane.showInputDialog(null,null,"Guess a number between 1 and 1000", JOptionPane.QUESTION_MESSAGE));
while(win == false){ //Potential infinite loop begins here...
numberOfTries++;
if(numberToGuess < guess1)
{
JOptionPane.showMessageDialog(null,"The number you guessed was to low. Please try again" ,null , JOptionPane.INFORMATION_MESSAGE);
}
else if(numberToGuess > guess1){
JOptionPane.showMessageDialog(null,"The number you guessed was to high. Please try again" ,null , JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "Congratulations you won. The number was " + numberToGuess + ". It took you " + numberOfTries, null, JOptionPane.INFORMATION_MESSAGE);
win = true;
}
}//Win == False
僅當win = true時,此循環才會退出。 但是,只有在猜出正確的數字后才能發生這種情況。 錯誤的數字輸入將導致循環無限繼續,因為用戶實際輸入數字的唯一時間是在循環輸入之前 。 您可以通過在消息對話框中顯示嘗試次數來證明這一點:您將看到隨后的每個對話框都會將嘗試次數增加一倍。
幸運的是,修復很容易:
while(win == false){
int guess1 = Integer.parseInt(JOptionPane.showInputDialog(null,null,"Guess a number between 1 and 1000", JOptionPane.QUESTION_MESSAGE)); //Moved this inside the loop
// ...rest is unchanged
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.