我在jgrasp上写了一个迷你小游戏。游戏提示用户猜测1到50之间的数字。然后while循环检查" if"声明并让他们知道他们是否猜到了#34;以及#34;或"低和#34;并提示他们再次猜测。我无法弄清楚如何跟踪用户猜测的数量。有小费吗??我是初学者程序员,感谢大家的帮助。
import java.util.Scanner;
public class Harrison6c {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the land of Hyrule!");
System.out.println("The land here is extremley dangerous");
System.out.println("Looks like you could use a sword");
System.out.println();
System.out.println("I'll tell you what lets play a game");
System.out.println("I have a number between 1 and 50");
System.out.println("Can you guess what it is?");
System.out.println("If you guess the number correctly");
System.out.println("I will give you something pretty cool!");
System.out.println();
int rand = (int)(Math.random() * (51 - 1)) + 1;
int guessInt;
guessInt = 0;
while (guessInt != rand) {
System.out.print("Enter your guess: ");
guessInt = input.nextInt();
guessInt++;
if (guessInt > rand) {
System.out.println("Guess lower");
System.out.println();
}
if (guessInt < rand) {
System.out.println("Guess higher");
System.out.println();
}
}
System.out.println("You got It!");
System.out.println("As promised here is your reward");
System.out.println("You've recieved the Kokiri Sword!");
System.out.println("Remember this land is very dangerous");
System.out.println("That sword you now yield shall protect you!");
System.out.println("You took" + guessInt++ + "guessess");
}
}
继承我的输出
----jGRASP exec: java Harrison6c
Welcome to the land of Hyrule!
The land here is extremley dangerous
Looks like you could use a sword
I'll tell you what lets play a game
I have a number between 1 and 50
Can you guess what it is?
If you guess the number correctly
I will give you something pretty cool!
Enter your guess: 50
Guess lower
Enter your guess: 30
Guess lower
Enter your guess: 20
Guess higher
Enter your guess: 25
Guess higher
Enter your guess: 24
Guess higher
Enter your guess: 27
Guess higher
Enter your guess: 28
Guess higher
Enter your guess: 29
You got It!
As promised here is your reward
You've recieved the Kokiri Sword!
Remember this land is very dangerous
That sword you now yield shall protect you!
You took30guessess
----jGRASP: operation complete.
答案 0 :(得分:3)
使用另一个变量将猜测次数增加为 -
int guessInt = 0;
int guesses = 0; // this would track the count of guesses
while( guessInt != rand) {
System.out.print( "Enter your guess: " );
guessInt = input.nextInt();
guesses++;
if(guessInt > rand) {
System.out.println("Guess lower");
System.out.println();
}
if(guessInt < rand) {
System.out.println("Guess higher");
System.out.println();
}
}
....
System.out.println("You took" + guesses + "guessess");
...
注意 - 您可以通过避免这些S.out
并有效使用\n
来清理代码。
答案 1 :(得分:0)