2015-09-17 47 views
0

Scanner.hasNext如果有令牌時讀取沒有令牌時它應該結束循環,但得到錯誤沒有這樣的元素髮現異常但當我切換第1行和第2行時我工作正常。掃描儀在循環結束後讀取

public class ScannerDemo { 

    public static void main(String[] args) { 

     String s = "Hello World! 3 + 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 the next is a long, print found and the long 
      // LINE 1 
      if (scanner.hasNextLong()) { 
       System.out.println("Found :" + scanner.nextLong()); 
      } 
      // if no long is found, print "Not Found:" and the token 
      // LINE 2 
      System.out.println("Not Found :" + scanner.next()); 

     } 
    } 
} 

錯誤

Not Found :Hello 
Not Found :World! 
Found :3 
Not Found :+ 
Not Found :3.0 
Not Found := 
Not Found :6.0 
Not Found :true 
Found :13964599874 
Exception in thread "main" java.util.NoSuchElementException 
    at java.util.Scanner.throwFor(Unknown Source) 
    at java.util.Scanner.next(Unknown Source) 
    at ScannerDemo.main(ScannerDemo.java:23) 
+0

是得到了我的愚蠢的錯誤,我沒有刪除了一個問題,另外一個可以做這種無聊的事情 – JSONParser

+0

你是什麼意思? –

+0

我應該刪除它嗎? – JSONParser

回答

1

使用的if else這樣

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

     System.out.println("Not Found :" + scanner.next()); 
} 

的問題是,如果有一個nextLong你在年底有調用next 2 times.but沒有更多的元素。

在你的代碼串是Hello World! 3 + 3.0 = 6.0 true 13964599874 覺得現在給你打電話nextLong,並且找到13964599874但是當你再打電話next()你的錯誤NoSuchElementException爲什麼呢?因爲之後什麼也沒有13964599874

1

那是因爲你不停止循環。它讀取Long後,它將繼續: System.out.println("Not Found :" + scanner.next());

修復它通過添加continueSystem.out.println("Found :" + scanner.nextLong());

 if (scanner.hasNextLong()) { 
      System.out.println("Found :" + scanner.nextLong()); 
      continue; 
     }