我该如何设置限制 [英] How can I set a limit
本文介绍了我该如何设置限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用Java编写了一个练习程序,计算机会在其内存中保存一个随机数,用户必须猜测它。每次用户猜错号码时,编译器要求再次尝试,但我想设置一个限制到该程序,如果用户猜测数字8次,则程序停止。任何帮助将不胜感激。
我尝试过:
I have made a practice program in Java in which computer will save a random number in it's memory and the user has to guess it. Everytime user guesses a wrong number, The compiler asks to try again,But i want to set a limit into that program that if the user guesses the number 8 times,then the program stops. Any help would be appreciated.
What I have tried:
public static void main(String[] args) {
Random nums = new Random();
int ran= nums.nextInt(100);
System.out.printf("Please enter a value: %n");
Scanner scan = new Scanner(System.in);
int Value1;
do {
Value1= scan.nextInt();
if(Value1 > ran) {
System.out.println("You entered "+ Value1 + " which is greater than guess Please try again:");
}else if (Value1 < ran){
System.out.println("You entered "+ Value1 + " which is lesser than guess Please try again:");
}else {
System.out.println("Good job");
}
/*int tries= 8;
for(int i=0; i ==tries;i++) {
if(Value1==i) {
System.out.println("Game Over");
}
}*/
}while(Value1!=ran);
scan.close();
}
推荐答案
这里是我的建议。包含一个变量来跟踪尝试次数。如果猜数> 8,显示消息,退出循环。如果用户猜出正确的数字,请立即退出循环。这是一个例子: https://www.jdoodle.com/embed/v0/zQq
注意:要测试它,请打开交互模式,然后单击执行按钮。
Here my suggestion. Include a variable to track number of attempt. If the number of guess > 8, display a message, exit the loop. If the user guess the correct number, exit the loop immediately. here is an example: https://www.jdoodle.com/embed/v0/zQq
Note: To test it, turn on the Interactive mode then click on Execute button.
这篇关于我该如何设置限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文