gpt4 book ai didi

Java while 循环游戏

转载 作者:行者123 更新时间:2023-11-29 02:59:52 25 4
gpt4 key购买 nike

我正在用 Java 编写一个程序,它需要我让用户仅尝试 10 次就可以猜出数字,还需要使用 while 循环。这就是我目前所拥有的,任何人都可以帮助我将 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++;

}
}

最佳答案

user guess the number with only 10 tries

 while(numberOfTries<10){
System.out.print("Guess number " + (numberOfTries+1) + ": ");
guess= input.nextInt();
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!");
break;
}

numberOfTries++;
}
// If after executing the while loop the numberOfTries is equal to 10, that means the user had made all attempt.
if(numberOfTries == 10){
System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
System.out.println("The number was" +numberToGuess);
}

这将替换您发布的所有声明

System.out.println ("You have 10 tries to guess a number between 1 and 100");

关于Java while 循环游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35788039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com