测试 ArrayList .txt文件是否存在错误(不符合允许的格式)



我正在尝试创建一个读取.txt文件并能够确定内容格式是否正确的 Java 程序。该文件应有 12 行,每行 2 个整数。我需要测试以下内容:

  • 如果每行有太多整数
  • 如果每行没有足够的整数
  • 如果它包含双精度而不是整数
  • 如果它包含字符串而不是整数

这是我到目前为止所拥有的:

import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
public class TextFileReader {
   public static void main(String[] args) {
      ArrayList<Integer> inputFile = new ArrayList<Integer>(20);
      Scanner fileScanner = null;
      try {
         fileScanner = new Scanner(new File("perfect_file.txt"));
         while (fileScanner.hasNext()) {
            inputFile.add(fileScanner.nextInt());
         }
      }
      catch (Exception ex) {
         System.out.println("Error reading generic answers, program ending.");
         System.exit(1);
      }
      fileScanner.close();
      for (int i = 0; i < inputFile.size(); i++) {
         if (inputFile.size() > 12) {
         }
      }
      if (inputFile.size() > 12) {
         System.out.println("Error: Lines exceed 12");
      }
      if (inputFile.size() < 12) {
         System.out.println("Error: Not enough lines");
      }
      System.out.println(inputFile);
   }
}

几点:

1( 使用 try with resources 语句,因为它会自动为您关闭所有资源(因此会为您调用fileScanner.close()。目前,如果抛出异常,则永远不会调用close()方法,因为您要阻止 JVM 运行。尝试资源的另一种方法是保持它的方式,但将close()放在finally块中

try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"))) {
} catch (FileNotFoundException e) {
    System.out.println("Error reading generic answers, program ending.");
    System.exit(1);
}

2(如果您调用fileScanner.nextInt()并且下一行不是整数,那么它将抛出一个InputMismatchException,因此更简单的方法是将该行扫描为字符串并检查字符串以进行更多控制...在这里,您可以从上面检查大部分情况

   List<Integer> ints = new ArrayList<>();
        byte lineCount = 0;
        try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"))) {
            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine();
                lineCount++;
                if (line.length() != 2) {
                    System.err.println("Line " + (lineCount + 1) + " has the wrong number of digits. Expected 2. Got: " + line.length());
                } else {
                    try {
                        ints.add(Integer.parseInt(line));
                    } catch (NumberFormatException e) {
                        System.err.println("Line " + (lineCount + 1) + " doesn't " +
                                "contain valid integers. Input: "" + line + "" - skipping line");
                    }
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("Error reading generic answers, program ending.");
            System.exit(1);
        }

3((琐碎(您的长度检查可以在 1 个语句中完成

if (inputFile.size() != 12) {
            System.out.println((inputFile.size() < 12 ? "Error: Not enough lines" : "Error: Too many lines")
                                + ". Expected 12. Got " + inputFile.size());
        }

最新更新