【发布时间】:2019-04-27 05:46:37
【问题描述】:
我想编写从文本文件中读取有理数并逐行添加它们的 Java 代码。数字用“和”隔开。但是,行的总和输入错误。
这些是文本文件的内容:
1234/5678and8765/4321
0/1and34/675
apple/23and23/x
-346/74and54/32
-232/884and-33/222
1.2/31and-1/4
-5and1/2
0and3/4
2/3and0
-4/5and5
我已经编写了一些代码,但是当输入错误时它会终止。我觉得可以改进
import java.io.*;
class ReadAFile{
public static void main(String[] args){
try{
File myFile = new File("input.txt");
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
while((line=reader.readLine())!=null){
String [] value = line.split("and");
String part1 = value[0];
String part2 = value[1];
String[] num = part1.split("/");
String[] dig = part2.split("/");
float x = Integer.parseInt(num[0]);
float y = Integer.parseInt(num[1]);
float a = x/y;
float p = Integer.parseInt(dig[0]);
float q = Integer.parseInt(dig[1]);
float b = p/q;
float sum = a + b;
System.out.println(sum);
}
reader.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
在输出中,我希望添加正确输入的每一行,同时跳过输入错误的行。
这是我目前的输出:
2.2457957
0.05037037
Exception in thread "main" java.lang.NumberFormatException: For input string: "apple"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at ReadAFile.main(ReadAFile.java:26)
【问题讨论】:
-
你想如何处理错误的输入:忽略/拒绝,制定协议或修复它(apple => 4543)。你需要自己的解析器。
标签: java