【问题标题】:Reading rational numbers from a text file line by line and add numbers in each line with some lines having wrong input逐行从文本文件中读取有理数,并在每行中添加数字,其中某些行输入错误
【发布时间】: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)

【问题讨论】:

标签: java


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用 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();
            }
        }
    }
    

    【讨论】:

    • 您的预检检查将捕获 OP 样本数据中的所有内容,但不会捕获所有错误输入。例如,输入中的“0-0”项仍然会导致异常,因为这不是有效的浮点数。
    • 非常感谢。程序正在运行。我不得不添加其他 if 语句来满足场景: num.length==1&&dig.length==2 和 num.length==2&&dig.length==1
    • @Steve 我已经更新了我的答案以处理无效的浮点数
    • 好的,看起来应该可以。尽管除了分割输入的工作之外,每行输入有 6 个正则表达式匹配,但似乎效率低下。为什么不编写一个正则表达式来测试整个输入行?
    【解决方案3】:

    您可以有效地处理这些行,既可以验证它们,也可以使用单个正则表达式解析它们。不需要所有的分裂,这会产生一堆东西的副本。这是一个这样的解决方案:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 2021-04-08
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多