2014-10-18 26 views
1

我遇到了一些問題,試圖讓我的代碼工作。我正在爲我的計算機科學課程開發一個項目,並且我必須讓我的程序讀取文件並執行一些數學運算。當我嘗試這樣做時,代碼無法工作。然後,我與一位寫出完全相同的代碼的朋友進行了覈對,結果無效。Integer.parseInt()問題

輸入.txt文件,該程序讀取看起來像這樣: 2/3,4/5 -1/6,2/4 1/1,1/1

我的代碼寫這個樣子的:

import javax.swing.JFileChooser; 

import java.util.*; 

public class ProjectTest 
{ 

    public static void main(String[] args) throws Exception 
    {   

     JFileChooser chooserRational = new JFileChooser(); 
     int returnValRational = chooserRational.showOpenDialog(null); 
     if(returnValRational == JFileChooser.APPROVE_OPTION) 
     { 
      System.out.println("You chose to open this file: " + chooserRational.getSelectedFile().getName()); 

      Scanner input = new Scanner(chooserRational.getSelectedFile()); 

      while(input.hasNext() == true) 
      { 
       String line = input.nextLine(); 
       String[] output = line.split(","); 
       String[] output1 = output[0].split("/"); 
       String[] output2 = output[1].split("/"); 

       String a = output1[0]; 
       String b = output1[1]; 
       String c = output2[0]; 
       String d = output2[1]; 

       int int1 = Integer.parseInt(a); 
       int int2 = Integer.parseInt(b); 
       int int3 = Integer.parseInt(c); 
       int int4 = Integer.parseInt(d); 

       System.out.println(int1 + " " + int2 + " " + int3 + " " + int4); 


      } 
      input.close(); 
     } 
    } 
} 

當我只輸出字符串A,b,c和d,代碼工作完全正常和完美的輸出值。當代碼看到Integer.parseInt(a),但是,它讓我看起來像這樣的錯誤:

Exception in thread "main" java.lang.NumberFormatException: For input string: "?2" 
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:580) 
    at java.lang.Integer.parseInt(Integer.java:615) 
    at ProjectTest1.main(ProjectTest1.java:33) 

任何幫助將不勝感激。

+2

input.hasNext()==真正是多餘的使用input.hasNext(),而不是 – 2014-10-18 08:32:42

+0

我只是貼+代碼複製到我的機器,它的工作沒有問題(java版「1.8。 0_05「) – msrd0 2014-10-18 08:39:26

+1

您的輸入文本是否包含」?2「。看起來你正在解析一個不是整數的字符串'?2'。所以,只需在調用Integer.parseInt之前打印出字符串,並確保字符串實際上是整數。 – 2014-10-18 08:40:11

回答

1

你應該

String line = input.next(); 

更換

String line = input.nextLine(); 

,因爲你有數據的倍數組在同一直線上。

編輯:

我跑你的代碼,並沒有得到同樣的異常,你。我有一個NumberFormatException由於nextLine調用,我現在修復它,它運行沒有錯誤。我認爲像其他人一樣,你有一個編碼問題。在互聯網上搜索如何在首選文本編輯器上顯示不可見字符。

2

因爲您的數據文件包含UTF-8 BOM

您有兩種選擇:編輯您的源數據文件以刪除BOM,或者您可以添加一些代碼來處理BOM。對於第一個選項,使用Notepad ++並刪除BOM。對於第二個選擇:

Scanner input = new Scanner(chooserRational.getSelectedFile()); 

if (input.nextByte() == 0xFE) { 
    input.nextByte(); 
    input.nextByte(); 
} else { 
    input = new Scanner(chooserRational.getSelectedFile()); 
}