2017-10-12 152 views
-3

我正在研究計算稅款的代碼。我希望這段代碼能夠確保用戶輸入一個有效的正整數。它工作除非輸入字符串,然後進入無限循環。如何讓它重複循環並讓用戶輸入另一個輸入,而不是無限循環?While Loop is Infinite

int dependentsRerun = 0;//makes user enter valid input for dependents 
    while(dependentsRerun == 0) { 
     System.out.println("Please enter number of dependents: "); 
     if(stdin.hasNextInt()) { 
      int dependents = stdin.nextInt(); 
      if(dependents>=0) { 
       dependentsRerun = 1; 
      }//end if dependents>=0 
      else {System.out.println("Invalid input");}//dependents negative 
     }//end if hasNextInt 
     else {System.out.println("Invalid input");}//dependents not an integer 
    }//end while dependentsRerun 
+1

請標記語言,例如C#或Java。 –

+0

'if(dependents> = 0)'永遠不會是真的。 – PHPglue

+0

當下一個輸入不是'int'時,你輸入一個無限循環。添加一個'stdin.next()'來使用該標記。 –

回答

0

您需要將代碼包圍在try塊中,然後捕獲InputMismatchException,然後捕獲輸入行以清除緩衝區。

int dependentsRerun = 0;//makes user enter valid input for dependents 
    while(dependentsRerun == 0) { 
     System.out.println("Please enter number of dependents: "); 
     try{ 
       int dependents = stdin.nextInt(); 
       if(dependents>=0) { 
        dependentsRerun = 1; 
       } 
       else { 
        System.out.println("Invalid input"); 
       } 
      }catch(InputMismatchException e){ 
       System.out.println("Invalid input"); 
       //catches input and clears 
       stdin.nextLine(); 
      } 
     } 

} 

編輯:

這可能是一個更好的方式來構建循環

 while(true) { 
     System.out.println("Please enter number of dependents: "); 
     try{ 
       int dependents = stdin.nextInt(); 
       if(dependents >= 0) { 
        //stops loop and moves on 
        break; 
       } 
       else { 
        System.out.println("Can't enter a negative number."); 
       } 
      }catch(InputMismatchException e){ 
       System.out.println("Invalid input"); 
       //catches input and clears 
       stdin.nextLine(); 
      } 
     } 
}