2017-10-04 5 views
0
長いか

イムとして数を決定するものではありません。連続した2つの数字を入力すると(スペースで区切られています)、最初の数字は長いと認識されますが、2番目の数字は認識されません。スキャナは、私が見つけたこのコードで実験しようとしている

import java.util.*; 

public class ScannerDemo { 

    public static void main(String[] args) { 

    String s = "Hello World! 35 62 + 3.0 = 6.0 true "; 
    Long l = 13964599874l; 
    s = s + l; 

    // create a new scanner with the specified String Object 
    Scanner scanner = new Scanner(s); 

    // find the next long token and print it 
    // loop for the whole scanner 
    while (scanner.hasNext()) { 

    // if no long is found, print "Not Found:" and the token 
    System.out.println("Not Found: " + scanner.next()); 

    // if the next is a long, print found and the long 
    if (scanner.hasNextLong()) { 
    System.out.println("Found: " + scanner.nextLong()); 
    } 

    } 

    // close the scanner 
    scanner.close(); 
    } 
} 

結果:なぜ62は

Not Found :Hello 
Not Found :World! 
Found :35 
Not Found :62 
Not Found :+ 
Not Found :3.0 
Not Found := 
Not Found :6.0 
Not Found :true 
Found :13964599874 

を見つけていませんか?あなたのコードで

+1

あなたが起こるか見てステップにより、デバッグやステップを使用しようとしたことがありますか? * 62 *はscanner.hasNext()によって読み取られ、次のステートメントは* Not Found *と表示されます。 – Alex

答えて

0

あなたが他の下では見られないコードを移動することができますを引っ張っ:

// if the next is a long, print found and the long 

    if (scanner.hasNextLong()) { 
     System.out.println("Found :" + scanner.nextLong()); 
    }else{ 
     System.out.println("Not Found :" + scanner.next()); 
    } 
+0

ありがとうございます。ちょうど不思議なことですが、条件の順序が重要です(この場合)?条件が満たされていないときは、それは次のように進むなどではありませんか?あなたもこれをクリアすることができれば幸いです。祝福の条件の – gendave

+0

@gendave順序は重要ではなく、あなたのケースでは、この条件を実行取得したのSystem.out.println(「見つかりませんでした:」+ scanner.next());条件付きチェックなしで条件付きブロック内にないので、常に実行されていたため、参照が次の項目に移動しました。 – theLearner

0

、「見つかりません」ラインは現在、そのコード行は要素が長いかであるかどうか、各反復で次の要素を取得しているように

if (!scanner.hasNextLong())

などの条件を必要としますない。だから、62は検出されていないが、35は検出されている。条件付きの2番目のステートメントで35が見つかると、最初のステートメントで62が処理されます。

0

あなたは、文字列の各単語を見て、ロングスにすることができる唯一のトークンをフィルタリングしようとすることができ

String s = "Hello World! 35 62 + 3.0 = 6.0 true "; 
    Long l = 13964599874l; 
    s = s + l; 
    Long temp; 

    for (String word : s.split("\\s+")) 
    { 
     if (word.length()>10 && word.length() < 20) { 
      try{ 
      Long.parseLong(word); 
      System.out.println(word+ " is a Long"); 

      }catch(IllegalArgumentException ex){ 

      } 
     } 

    } 

出力:これにより

13964599874 is a Long 

あなたも署名排除する整数。これだけのように、ロングタイプ

+0

Stringの内部に長い文字列を追加すると、長さが認識されません。 – gendave

関連する問題