我正在做一個java程序,需要我讓用戶猜測只有10次嘗試的數字,並使用while循環。這是我現在所有的,任何人都可以幫助我在何處放置while循環以及我錯過了什麼?謝謝。Java while循環遊戲
import java.util.Scanner;
import java.util.Random;
public class GuessGame {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Random generator = new Random();
Scanner input = new Scanner(System.in);
int numberToGuess = 1 + generator.nextInt(100);
int numberOfTries = 0;
int limit= 10;
int guess;
System.out.println ("You have 10 tries to guess a number between 1 and 100");
System.out.print("Guess number 1: ");
guess= input.nextInt();
numberOfTries++;
if (guess < numberToGuess)
System.out.println("Your guess is too low. Try again.");
else if (guess > 100)
System.out.println("Guesses should be between 1 and 100.");
else if (guess > numberToGuess)
System.out.println("Too high. Try again.");
else if (guess == numberToGuess)
System.out.println("Congratulations!");
System.out.print("Guess number 2: ");
guess= input.nextInt();
numberOfTries++;
System.out.print("Guess number 3: ");
guess= input.nextInt();
numberOfTries++;
System.out.print("Guess number 4: ");
guess= input.nextInt();
numberOfTries++;
System.out.print("Guess number 5: ");
guess= input.nextInt();
numberOfTries++;
System.out.print("Guess number 6: ");
guess= input.nextInt();
numberOfTries++;
System.out.print("Guess number 7: ");
guess= input.nextInt();
numberOfTries++;
System.out.print("Guess number 8: ");
guess= input.nextInt();
numberOfTries++;
System.out.print("Guess number 9: ");
guess= input.nextInt();
numberOfTries++;
System.out.print("Guess number 10: ");
guess= input.nextInt();
numberOfTries++;
}
}
謝謝你,偉大的工作。在猜測數字後,如何結束循環? – worgenfreeman
放了一個'break;'..更新了 – nullpointer
謝謝大家!我還有一個問題,在用戶全部10次嘗試錯誤之後,我必須出現一條丟失消息。如何在10次嘗試後出現它? while(numberOfTries == 10){System.out.println(「對不起,你猜猜10次嘗試中的答案」); System.out.println(「數字是」+ numberToGuess);打破 – worgenfreeman