如何使用Scanner参考用户输入的最后一个值?

时间:2015-10-18 23:50:18

标签: java

我正在使用while循环来清除少于100的用户输入,然后让它们输入值,直到它们满足> = 100的条件。

但是一旦输入值> = 100,就必须再次输入它才能定义它,因为while循环执行getLength一次,然后更新int length再次执行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

所以不要输出:

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

我希望它有这个:

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

基本上,我是否可以获得由while循环提示的先前输入的用户输入?

1 个答案:

答案 0 :(得分:0)

您可以使用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;

通过这种方式,您可以将输入的最后一个值指定为长度。