2014-02-23 55 views
1

我正在寫一個JAVA類來驗證輸入數據,特別是整數。 我開發的類運行良好,但是當我按下多於一次輸入,然後是一個字符類型時,它顯示多次「錯誤!!無效的數字,再試一次」,我想避免它。如何避免按幾次輸入影響輸入數據?

我有使用nextLine()方法,但它似乎並沒有糾正它。

這裏是類:

package chapter07.libro; 

import java.util.Scanner; 

public class Validator_integer 

{ 

    public static int getInt (Scanner scanner, String promt) 

    { 
     int numberInteger = 0; 
     boolean isValid = false; 

     System.out.println(promt); 
     while(isValid == false) 
     { 
      if(scanner.hasNextInt()) 
      { 
       numberInteger= scanner.nextInt(); 
       isValid = true; 
      }//if 

      else 
      { 
       System.out.println("Error!! Invalid number. Try again."); 
      }//else 
      scanner.nextLine();   
     }//while 

     return numberInteger; 
    }//getInt 

}//Validator_integer 

旁邊是使用類的應用:

package chapter.prueba; 

import java.util.Scanner; 

import chapter07.libro.Validator_integer; 

public class Test_Validator_Integer 

{ 

    public static void main(String[] args) { 

     Scanner sc = new Scanner (System.in); 
     String choice = "y"; 

     while(choice.equalsIgnoreCase("y")) 
     { 
      int number = Validator_integer.getInt(sc, "Enter integer number: "); 
      System.out.println(number); 

      System.out.println("Continue (y/n): "); 
      choice = sc.next(); 

     }//while 

    }//main 

}//Test_Validator_Integer 

結果我得到的是未來:

Enter integer number: 

2 

2 

Continue (y/n): 

y 

Enter integer number: 

(Here I press several time enter) 

xx 

Error!! Invalid number. Try again. 

Error!! Invalid number. Try again. 

Error!! Invalid number. Try again. 

Error!! Invalid number. Try again. 

2 

2 

Continue (y/n): 

n 

所以部分(錯誤!!無效的號碼,再試一次。)顯示多次,是我想避免的。

是否有人知道如何解決它? 在此先感謝!

+0

您是否嘗試過在嘗試讀取前沖洗System.in?這樣,任何緩衝/排隊的輸入都將被刪除。 'code'其他 \t \t \t { \t \t \t \t \t: –

回答

0

在從System.in讀取之前,請確保清除它的內容以擺脫緩衝/排隊輸入。如果有n個字符排隊,那麼跳過那麼多字符,你需要輸入新的東西。

int n = System.in.available(); 
System.in.skip(n); 

http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

+0

感謝馬庫斯,爲了刪除quenue我發現簡單的else statment中添加下一個代碼(按ENTER鍵數次生成) \t \t \t String string = scanner.nextLine(); \t // NEW \t \t \t \t而(string.isEmpty())\t \t \t \t \t // NEW \t \t \t \t \t {\t \t \t \t \t \t \t \t \t // NEW \t \t \t \t \t字符串=掃描儀。nextLine(); \t \t // NEW \t \t \t \t \t \t \t \t \t} //而\t \t \t \t \t \t \t \t // NEW \t \t \t \t \t \t \t \t \t //scanner.nextLine(); \t \t \t \t \t // DELETE \t \t \t \t的System.out.println( 「錯誤!無效號碼重試。」。); \t \t \t} //別的'code' – MauricioTL