首页 > 解决方案 > 逐行从文本文件中读取有理数,并在每行中添加数字,其中某些行输入错误

问题描述

我想编写从文本文件中读取有理数并逐行添加它们的 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)

标签: java

解决方案


Integer.parseInt 抛出 NumberFormatException,因此您将需要 try/catch 块。


推荐阅读