Integer.parseInt()问题

时间:2014-10-18 08:30:06

标签: java 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 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分:1)

你应该替换

String line = input.nextLine();

String line = input.next();

因为您在同一行上有多个数据组。

修改:

我运行了你的代码并没有得到与你相同的异常。由于NumberFormatException调用,我有一个nextLine,我现在修复了它,它运行时没有错误。我认为和其他人一样,你有编码问题。在互联网上搜索如何在首选文本编辑器上显示不可见字符。

相关问题