我正在寫一個java代碼,要求用戶猜測計算機的隨機數,我很好,但是,我想要做的是有一個消息對應的猜測數拿走了用戶。猜數字遊戲java
例如,如果用戶猜測1中的隨機數,嘗試輸出「優秀!」。如果用戶猜到2-4的答案嘗試「好工作」等。
我想我還沒有嘗試過任何東西,因爲我不知道在哪裏粘住代碼?
我知道它必須如果猜== = 1然後做這個如果代碼> 1 < = 3然後這樣做等等..但在我的代碼?它應該在嵌套if的while循環中嗎?
這是我更新的代碼,它運行並編譯我創建它所需的確切方式。感謝所有的幫助!
public static void main(String[] args) {
Random rand = new Random();
int compNum = rand.nextInt(100);
int count = 0;
Scanner keyboard = new Scanner(System.in);
int userGuess;
boolean win = false;
while (win == false){
System.out.print("Enter a guess between 1 and 100: ");
userGuess = keyboard.nextInt();
count++;
if(userGuess < 1 || userGuess > 100){
System.out.println("Your guess is out of range. Pick a number between 1 and 100.");
System.out.println();
}
else if (userGuess == compNum){
win = true;
System.out.println("Congratulations! Your answer was correct! ");
}
else if (userGuess < compNum){
System.out.println("Your guess was too low. Try again. ");
System.out.println();
}
else if (userGuess > compNum){
System.out.println("Your guess was too high. Try again. ");
System.out.println();
}
}
if(count == 1){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was lucky!");
}
else if (count > 1 && count <= 4){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was amazing!");
}
else if (count > 4 && count <= 6){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was good.");
}
else if (count > 6 && count <= 7){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was OK.");
}
else if (count > 7 && count <= 9){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was not very good.");
}
else if (count > 10){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("This just isn't your game.");
}
}
}
你需要做的是向我們展示有問題的代碼並解釋你所嘗試過的代碼。你的問題有被關閉的危險,因爲除了你的目標之外,你還沒有提供任何相關的細節。首先決定如何將猜測次數映射到「獎勵」短語,然後編寫代碼來實現該映射。 –
創建一個函數,它將獲取的嘗試次數作爲參數,並返回一個包含所需消息的字符串。你需要使用某種控制結構來實現這一點,最簡單的可能只是一堆if-else語句。至於這個問題,這裏沒有主題,因爲很難真正給你一個簡潔的答案,包括你試圖解決問題的一些代碼會很好。 – shuttle87
對不起,就像我在這裏說的很新,看到了一些關於代碼的帖子,但它與我的問題沒有關係。我想我需要幫助的是如何將它嵌入我的代碼中,是否應該將它放在一個大的嵌套循環中?對不起,我試圖找出如何添加我的代碼,以顯示我有什麼.. –