2012-02-09 89 views
3

我怎麼能說以下內容:雖然不是條件

while(input is not an int){ 
do this 
} 

我想這個代碼,但我知道這是錯誤的:

int identificationnumber; 
Scanner sc3 = new Scanner(System.in); 
identificationnumber = sc3.nextInt(); 

while(identificationnumber != int){ // this line is wrong 

Scanner sc4 = new Scanner(System.in); 
identificationnumber = sc4.nextInt(); 

} 

任何建議please.Thanks。

+0

因此你得到一個int並且想檢查它是否不是一個?那麼還有什麼呢? – guitarflow 2012-02-09 00:49:10

+0

http://stackoverflow.com/questions/2674554/how-know-a-variable-type-in​​-java – AJP 2012-02-09 00:50:47

回答

0

通過編寫sc3.nextInt()我假設你總是得到一個int,所以檢查一個非int看起來有點奇怪。

也許最好是返回一個字符串與數字裏面。如果字符串是空的停止(您可以檢查「」),否則將其轉換爲整數。

+0

我使用sc3.nextInt來獲取輸入到一個int變量。 – 2012-02-09 10:58:01

+0

一個hasNextInt方法確實是更好的解決方案。 – 2012-02-09 11:29:49

6

嘗試:

while (! scanner.hasNextInt()) { // while the next token is not an int... 
    scanner.next();    // just skip it 
} 
int i = scanner.nextInt();  // then read the int 
0

使用nextInt()掃描器類的方法。

它拋出,

InputMismatchException - 如果下一個標記不匹配 Integer正則表達式,或者超出範圍

1

你想這個?

String identificationnumber; 
Scanner scanner = new Scanner(System.in);//Only one Scanner is needed 

while (scanner.hasNext()) { // Is there has next input? 
    identificationnumber = scanner.next();//Get next input 
    try { 
     Integer.parseInt(identificationnumber);//Try to parse to integer 
     System.out.println(identificationnumber + " is a number!"); 
    } catch (NumberFormatException e) { 
     System.out.println(identificationnumber + " is not a number!"); 
    } 
} 
+0

感謝你 - 但它只是讓我陷入無限循環。有沒有一種方法可以用for循環做到這一點? – 2012-02-09 10:56:22

+0

@ayokunleadeosun如果你想打破循環,你可以定義一個結束標誌字符串或只是使用「控制+ c」 – plucury 2012-02-09 13:41:33