【发布时间】:2017-03-01 05:02:25
【问题描述】:
我正在写一个关于 jgrasp 的小游戏。游戏提示用户猜测 1 到 50 之间的数字。然后,while 循环检查“if”语句,让他们知道他们猜到“高”还是“低”,并提示他们再次猜测。我不知道如何跟踪用户的猜测次数。有小费吗??我是初学程序员,谢谢大家的帮助。
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.
【问题讨论】:
-
在循环内增加一个变量。
-
我试过这样做,它打印出错误的数字我想我应该添加我的代码以获得反馈,请给我一秒钟。
-
如果你写了一些代码,请把它贴在这里,也许有人可以帮助你。
-
最好的办法是按照stackoverflow.com/help/mcve 的描述发布一个最小、完整和可验证的示例。
-
我知道我的增量变量有问题,但我就是想不通
标签: java while-loop