2016-06-21 2 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"); 

私は「もし」条件内での入力を取得していた場合にどのようにそれは、ユーザーが整数を入力したかどうか知っているのですか? Javaドキュメントによれば

+0

@Okx、hasNextInt(int radix)を呼び出します、ああ、それはうまく動作します。 – Asker

+0

あなたが作成するすべての質問はタイトルに「Java」で始まるので、「それをやめてください」(http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles)。 – Tom

答えて

2

hasNextIntは()「は、このスキャナの入力内の次のトークンをint値として解釈することができる場合に真を返します。」したがって、このメソッドは入力を調べ、その中の次のものが整数の場合はtrueを返します。スキャナは、変数を変数に入れることによって、入力をまだ読み取っていません。

+0

しかし、基数はどういう意味ですか?読み込む文字数は?または、intの行の文字の総数? – 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()はちょうどdefaultRadix = 10

public boolean hasNextInt() { 
    return hasNextInt(defaultRadix); 
} 
関連する問題