[英]How can I refer to the last value input by the user using Scanner?
I'm using a while loop in order to weed out user input of less than 100 and then make them enter values until they satisfy the condition of being >=100. 我正在使用while循环,以清除小于100的用户输入,然后使它们输入值,直到满足> = 100的条件为止。
But once a value >=100 is entered they would have to enter it again for it to be defined, since the while loop executes getLength once and then updating the int length executes getLength a second time. 但是一旦输入值> = 100,就必须再次输入该值以进行定义,因为while循环执行一次getLength,然后更新int长度再次执行getLength。
while(getLength.nextInt() < 100) //asks user to enter value to check if its less than 100
{
System.out.print("You have entered a value less than 100, please enter a value equal to or greater than 100:\n");
}
int length = getLength.nextInt(); //this makes the user have to enter it again
So instead of outputting: 因此,与其输出:
25 You have entered a value less than 100, please enter a value equal to or greater than 100: 50 You have entered a value less than 100, please enter a value equal to or greater than 100: 125 //while loop 125 //defining int length
I want it to have this: 我希望它有这个:
25 You have entered a value less than 100, please enter a value equal to or greater than 100: 50 You have entered a value less than 100, please enter a value equal to or greater than 100: 125 //prompted by while loop, value is used to define int length
Essentially, can I get the previously entered user input that was prompted by a while loop? 本质上,我可以获取while循环提示的先前输入的用户输入吗?
You can take an int variable where the user input can be saved. 您可以使用一个int变量,可以在其中保存用户输入。
int x;
while((x = getLength.nextInt()) < 100 )
{
System.out.println("You have entered a value less than 100, please enter a value equal to or greater than 100");
}
int length = x;
By this way you can assign the last value entered to length. 通过这种方式,您可以将最后输入的值分配给length。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.