2014-10-18 74 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()); 
}