我想编写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)
答案 0 :(得分:0)
Integer.parseInt引发NumberFormatException,因此您将需要try / catch块。
答案 1 :(得分:0)
您可以有效地处理这些行,既可以验证它们,又可以使用单个正则表达式对其进行解析。无需进行所有拆分,因为拆分会产生很多东西。这是一个解决方案:
public static void main(String[] args){
try {
File myFile = new File("/tmp/input.txt");
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
// The expression for a single float
String floatPat = "([-+]?[0-9]*\\.?[0-9]+)";
// Construct expression that models our input...two terms separated by 'and',
// each of which is a float followed optionally by a slash and a second float.
String fullPat = "@(/@)?and@(/@)?".replace("@",floatPat);
Pattern pat = Pattern.compile(fullPat);
String line = null;
while((line=reader.readLine())!=null) {
// Skip empty lines
if (line.isEmpty())
continue;
// apply our expression. If it matches, process the line
Matcher m = pat.matcher(line);
if (m.matches()) {
// Pull the first value of the first term out of the match
float x = Float.parseFloat(m.group(1));
// If the first term had a second part, pull out that float
float y = (m.group(3) == null)? 1.0f : Float.parseFloat(m.group(3));
float a = x / y;
// Pull the first value of the second term out of the match
float p = Float.parseFloat(m.group(4));
// If the second term had a second part, pull out that float
float q = (m.group(6) == null)? 1.0f : Float.parseFloat(m.group(6));
float b = p / q;
float sum = a + b;
System.out.println(sum);
}
else {
// Do something with bad input
System.out.println("Bad input: " + line);
}
}
reader.close();
}
catch (IOException ex){
ex.printStackTrace();
}
}
请注意,在这里,我也选择打印无效行,并注明。
输出:
2.2457957
0.05037037
Bad input: apple/23and23/x
-2.9881759
-0.4110921
-0.21129033
-4.5
0.75
0.6666667
4.2
答案 2 :(得分:0)
使用 regex(“ [0-9 /.-]+")来验证零件数据是否仅包含有理数。您必须使用Float.parseFloat()代替parseInt( )。 parseInt会为浮点数抛出NumberFormatException。
例如::在解析文件中的第6行(Integer.parseInt(“ 1.2”);)时,将引发NumberFormatException。
package com.stackovflow.problems;
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;
String onlyFloatNumRegex = "-?[0-9.]+";
while ((line = reader.readLine()) != null) {
String[] value = line.split("and");
if (value.length == 2) {
String part1 = value[0];
String part2 = value[1];
if (part1.matches("[0-9/.-]+") && part2.matches("[0-9/.-]+")) {
String[] num = part1.split("/");
String[] dig = part2.split("/");
if (num.length == 2 && dig.length == 2 && num[0].matches(onlyFloatNumRegex) && num[1].matches(onlyFloatNumRegex)
&& dig[0].matches(onlyFloatNumRegex) && dig[1].matches(onlyFloatNumRegex)) {
float x = Float.parseFloat(num[0]);
float y = Float.parseFloat(num[1]);
float a = x / y;
float p = Float.parseFloat(dig[0]);
float q = Float.parseFloat(dig[1]);
float b = p / q;
float sum = a + b;
System.out.println(sum);
}
}
}
}
reader.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}