【发布时间】:2014-10-18 08:30:05
【问题描述】:
我在尝试让我的代码正常工作时遇到了一点问题。我正在为我的计算机科学课做一个项目,我必须让我的程序读取文件并执行一些数学运算。当我尝试这样做时,代码不起作用。然后我咨询了一位编写完全相同代码的朋友,但没有成功。
程序读取的输入 .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)
任何帮助将不胜感激。
【问题讨论】:
-
input.hasNext() == true 是多余的使用 input.hasNext() 代替
-
我只是将代码复制+粘贴到我的机器上,它可以正常工作(java版本“1.8.0_05”)
-
您的输入文本是否包含“?2”。看起来您正在解析一个不是整数的字符串 '?2'。因此,只需在调用 Integer.parseInt 之前打印出字符串,并确保字符串实际上是整数。