您好,我正在尝试使用 Math.random 生成 0 到 100 之间的随机数,然后要求用户输入 0 到 100 之间的数字,或 -1 退出。如果数字超出范围(且不是 -1),请要求用户输入新数字。如果用户没有正确猜出数字,则告诉用户随机数是否高于或低于猜测的数字。让用户猜测,直到他们输入正确的数字或输入 -1。如果他们猜对了正确的数字,请告诉用户尝试了多少次,然后重新开始游戏。它将继续播放,直到用户退出。
我被困在如何只让用户输入 0-100 以及如何通过输入 -1 退出循环
这就是我到目前为止所拥有的,任何帮助将不胜感激!
import java.util.Scanner;
public class QuestionOne
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
int a = 1 + (int) (Math.random() * 99);
int guess;
System.out.println("Guess a number between 0-100");
while(guess != a){
guess = keyboard.nextInt();
if (guess > a)
{
System.out.println("The number is lower!");
}
else if (guess < a)
{
System.out.println("higher!");
}
else
{
System.out.println("Congratulations.You guessed the number with" + count + "tries!");
}
}
}
}
首先,对 Keyboard.nextInt() 的调用(及其相应的 println“猜测 0-100 之间的数字”)应该在 while 循环内。
那么你应该考虑将 while 循环更改为
while (true) {
// read input from user
if (guess < value) { // tell user their guess is too low
} else if (guess > value) { // tell user their guess is too high
} else { // tell user congrats, and call break to exit the while loop }
}
}
一旦你做对了,你就可以做一些必要的事情,比如检查猜测的数字是否在范围内,跟踪他们完成了多少次猜测,等等
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)