java - 逐行从文本文件中读取有理数,并在每行中添加数字,其中某些行输入错误
问题描述
我想编写从文本文件中读取有理数并逐行添加它们的 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)
解决方案
Integer.parseInt 抛出 NumberFormatException,因此您将需要 try/catch 块。
推荐阅读
- c# - C/C# fork vs thread vs bg worker?
- image - 检索图像附件的替代文本?
- c# - 如何在主机上运行 .asp 网络 Web 应用程序?
- javascript - Bootstrap 5 输入文本 - 右对齐
- javascript - 带有动态参数的 Vue Js API 调用
- mysql - React Native + mySQL - 在我的应用程序中获取数据
- mysql - 有没有办法在自联接表中找到最大值?
- javascript - 如何向动态导入的模块添加其他内容?
- vulkan - 在同一个附件中渲染多个 vulkan 通道
- vim - 由于 try 命令而卡在 vim 中