2015-10-23 85 views
0

我在寫一個從文本文件讀取運動數據的程序。每行都有字符串和整數混合在一起,我試圖只讀取團隊的分數。但是,即使這些行有整數,程序也會立即轉到else語句而不打印分數。我有兩個input2.nextLine()語句,以便它跳過兩個沒有分數的標題行。我怎樣才能解決這個問題?掃描儀/令牌錯誤java

下面的代碼:

public static void numGamesHTWon(String fileName)throws FileNotFoundException{ 
    System.out.print("Number of games the home team won: "); 
    File statsFile = new File(fileName); 
    Scanner input2 = new Scanner(statsFile); 


    input2.nextLine(); 
    input2.nextLine(); 

    while (input2.hasNextLine()) { 
     String line = input2.nextLine(); 
     Scanner lineScan = new Scanner(line); 
     if(lineScan.hasNextInt()){ 

      System.out.println(lineScan.nextInt()); 
      line = input2.nextLine(); 

     }else{ 
      line = input2.nextLine(); 



     } 
    } 
} 

這裏是文本文件的頂部:

NCAA Women's Basketball 
2011 - 2012 
2007-11-11 Rice 63 @Winthrop 54 O1 
2007-11-11 @S Dakota St 93 UC Riverside 90 O2 
2007-11-11 @Texas 92 Missouri St 55 
2007-11-11 Tennessee 76 Chattanooga 56 
2007-11-11 Mississippi St 76 Centenary 57 
2007-11-11 ETSU 75 Delaware St 72 O1 Preseason NIT 
+0

對不起,你試圖準確產生什麼輸出以及出了什麼問題? – Pshemo

+0

在這一點上,我只是想從每一行讀取整數,我試圖將它們輸出到控制檯,只是爲了檢查整數是否確實被掃描器讀取,但是,它們不是因爲程序自動進入else語句並停止。 – Hector

+1

你認爲'lineScan.hasNextInt()'應該返回什麼?你爲什麼這麼認爲? 'hasNextInt'方法的哪部分文檔讓你認爲你的假設是正確的? – Pshemo

回答

0

方法hasNextInt()嘗試檢查立即字符串爲int? 。所以這種情況不起作用。

public static void numGamesHTWon(String fileName) throws FileNotFoundException { 
     System.out.print("Number of games the home team won: "); 
     File statsFile = new File(fileName); 
     Scanner input2 = new Scanner(statsFile); 


     input2.nextLine(); 
     input2.nextLine(); 

     while (input2.hasNextLine()) { 
      String line = input2.nextLine(); 
      Scanner lineScan = new Scanner(line); 

      while (lineScan.hasNext()) { 
       if(lineScan.hasNextInt()) { 
        System.out.println(lineScan.nextInt()); 
        break; 
       } 
       lineScan.next(); 
      } 
      line = input2.nextLine(); 
     } 
} 

請試試這段代碼。

+0

我在lineScan.next()中得到一個「java.util.NoSuchElementException:null(在java.util.Scanner)」錯誤。部分(倒數第二行) – Hector

+0

我錯過了break語句。你可以請現在嘗試。 –

+0

它只在左側輸出每隔一個分數。 – Hector