2015-10-18 37 views
1

我使用while循環爲了淘汰用戶輸入少於100,然後讓他們輸入值,直到他們滿足> = 100的條件。如何引用用戶使用掃描儀輸入的最後一個值?

但是,一旦輸入值> = 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 

因此,而不是輸出:

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循環提示?

回答

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; 

通過這種方式,您可以將最後輸入的值分配給長度。