2012-11-25 139 views
0

我目前有一個簡單的函數(下面發佈),詢問用戶一個問題,並期望有一個整數的答案。按字符類型限制控制檯輸入

有沒有辦法讓java限制可以輸入到控制檯的字符,即只允許輸入數字。

我知道有很多簡單的方法可以在其他編程語言中做到這一點,但我應該如何去做這個在java中,並將其實現到我的功能?

static int questionAskInt(String question) 
{ 
    Scanner scan = new Scanner (System.in); 
    System.out.print (question+"\n"); 
    System.out.print ("Answer: "); 
    return scan.nextInt(); 
} 

回答

0

使用Scanner.hasNextInt,和while循環,可以限制用戶給出的輸入,直到它通過一個integer值。

while (!scan.hasNextInt()) { 
    System.out.println("Please enter an integer answer"); 
    scan.next(); 
} 
return scan.nextInt(); 

或者,你也可以給一定數量的機會(這樣不會進入infinite loop,通過使用一個計數變量: -

int count = 3; 

while (count > 0 && !scan.hasNextInt()) { 
    System.out.println("Please enter an integer answer"); 
    System.out.println("You have " + (count - 1) + "more chances left."); 
    count--; 
    scan.next(); 
} 

if (count > 0) { 
    return scan.nextInt(); 
} 

return -1; 
+0

目前正在嘗試輸入一些字符,是經過沒有一個int和按下輸入這陷入了無盡的循環垃圾郵件「請輸入一個整數的答案」有沒有更好的方法? –

+0

@ mr.user1065741 ..嘗試我發佈的第二種方式。 –

+0

@ mr.user1065741 ..採取第二代碼的最新編輯 –