2016-06-21 82 views
0

好吧,所以我是一個完整的初學者,如果這對你來說真是一個愚蠢的問題,我很抱歉。掃描儀類方法

所以我開始使用Scanner類,而對我而言似乎有些奇怪。

例如,這行代碼:

Scanner scan = new Scanner(System.in); 

System.out.print("Write string: "); 

if(scan.hasNextInt()){ 

    int x = scan.nextInt(); 
} 
else 
    System.out.println("Only integers allowed"); 

它是如何知道用戶是否輸入了一個整數或沒有,如果我只得到了「如果」條件內的輸入?

+0

@Okx ,哦,它工作得很好。 – Asker

+0

由於您創建的每個問題都以標題中的「Java」開頭:[停止這樣做](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles)。 – Tom

回答

2

根據Java文檔:「如果在此掃描器輸入信息的下一個標記可以解釋爲一個int值返回true」

hasNextInt()所以這個方法查看輸入,如果下一個東西是一個整數,它返回true。掃描儀還沒有通過將其輸入到變量中來「讀取」輸入。

+0

但基數是什麼意思?要讀取的字符數量?或者是整行上的字符總數? – Azurespot

0

如果你看一下實際執行hasNextInt,然後就可以看到它是如何知道:

/** 
* Returns true if the next token in this scanner's input can be 
* interpreted as an int value in the specified radix using the 
* {@link #nextInt} method. The scanner does not advance past any input. 
* 
* @param radix the radix used to interpret the token as an int value 
* @return true if and only if this scanner's next token is a valid 
*   int value 
* @throws IllegalStateException if this scanner is closed 
*/ 
public boolean hasNextInt(int radix) { 
    setRadix(radix); 
    boolean result = hasNext(integerPattern()); 
    if (result) { // Cache it 
     try { 
      String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? 
       processIntegerToken(hasNextResult) : 
       hasNextResult; 
      typeCache = Integer.parseInt(s, radix); 
     } catch (NumberFormatException nfe) { 
      result = false; 
     } 
    } 
    return result; 
} 

注意hasNextInt()只是調用hasNextInt(int radix),其中defaultRadix = 10

public boolean hasNextInt() { 
    return hasNextInt(defaultRadix); 
}