對於我的Java類,我正在編寫一個小程序,首先選取1到100之間的int
數字。然後提示用戶開始猜測正確的int
。如果用戶猜測int
太高或太低,程序會打印出一個新的範圍供他們猜測。如果用戶輸入String
或double
,則程序簡單地重新要求用戶輸入int
,但不以任何方式改變範圍。在一定數量範圍內保留範圍
樣品輸出(當保密號20)將如下所示:
c:\csc116> java GuessingGame Guess the secret number! Enter a number between 1 and 100 (inclusive): 45 Enter a number between 1 and 44 (inclusive): jlkj Enter a number between 1 and 44 (inclusive): 31.0 //double Enter a number between 1 and 44 (inclusive): 1000 //outside the range of 1-100 Enter a number between 1 and 44 (inclusive): 34 Enter a number between 1 and 33 (inclusive): 15 Enter a number between 16 and 33 (inclusive): 20 You win!
節目似乎是幾乎沒有,但有一個例外。其中一個要求是,當用戶鍵入的int
超出我們給定的1和100範圍時,打印輸出消息不會改變(如上例所示)。這是我陷入困境的地方,我期待着看有沒有人能幫助我指導正確的答案。
import java.util.*;
public class GuessingGame {
public static void main(String[] args) {
introduction();
Scanner console = new Scanner(System.in);
Random rand = new Random();
int guess = 0;
int minimum = 1;
int maximum = 100;
int secretNumber = rand.nextInt(100) + 1;
System.out.print("Enter a number between " + minimum + " and " + maximum + " (inclusive): ");
while (guess != secretNumber) {
if (console.hasNextInt()) {
guess = console.nextInt();
if (guess > secretNumber) {
maximum = guess - 1;
System.out.print("Enter a number between " + minimum + " and " + maximum + " (inclusive): ");
}
if (guess < secretNumber) {
minimum =guess + 1;
System.out.print("Enter a number between " + minimum + " and " + maximum + " (inclusive): ");
}
if (guess == secretNumber) {
System.out.println("You win!");
}
} else {
console.next();
System.out.print("Enter a number between " + minimum + " and " + maximum + " (inclusive): ");
}
}
}
public static void introduction() {
System.out.println("Guess the secret number!");
}
}
你是什麼意思的「打印出來的消息不會改變」?它打印了「輸入一個介於1和44之間的數字(包含):」在輸入超出範圍數字之前和之後。它對我來說看起來是一樣的。 –
這意味着如果最初的打印輸出是「輸入一個介於1和100之間的數字」,並且用戶首先輸入4,那麼下一個打印輸出將是「輸入介於5和100之間的數字」。但是,如果用戶然後輸入1000,而不是1到100之間的整數,下一次打印輸出仍然會顯示「輸入5到100之間的數字」,而不是「輸入5到999之間的數字」。希望這樣可以清楚地表明我有時無法解釋自己。 – Rivers31334
哦,對不起,我錯誤地將您的示例輸出誤認爲您的實際輸出。 –