我遇到了一些問題,試圖讓我的代碼工作。我正在爲我的計算機科學課程開發一個項目,並且我必須讓我的程序讀取文件並執行一些數學運算。當我嘗試這樣做時,代碼無法工作。然後,我與一位寫出完全相同的代碼的朋友進行了覈對,結果無效。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)
任何幫助將不勝感激。
input.hasNext()==真正是多餘的使用input.hasNext(),而不是 – 2014-10-18 08:32:42
我只是貼+代碼複製到我的機器,它的工作沒有問題(java版「1.8。 0_05「) – msrd0 2014-10-18 08:39:26
您的輸入文本是否包含」?2「。看起來你正在解析一個不是整數的字符串'?2'。所以,只需在調用Integer.parseInt之前打印出字符串,並確保字符串實際上是整數。 – 2014-10-18 08:40:11