如何扫描 ArrayList 索引中的整数量



>我正在尝试制作一个程序来检查 ArrayList,并确保每个索引每行仅包含 2 个整数,并且不包含任何双精度或字符串。

如果数组列表是:

0 1
2 34
32 51 32

它会为第三行拉出一条错误消息,因为它有 3 个整数。程序需要检查它每行只有两个整数,只有 12 行长,并且不包含任何双精度或字符串。这是我到目前为止所拥有的:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class TextFileReader {
public static void main(String[] args) {
int fileCount = 0;
ArrayList<String> inputFile = new ArrayList<String>(20);
try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"))) {
while (fileScanner.hasNext()) {
inputFile.add(fileScanner.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("Error reading generic answers, program ending.");
System.exit(1);
}


if (inputFile.size() > 12) {
System.out.println("Error: Lines exceed 12");
}
if (inputFile.size() < 12) {
System.out.println("Error: Not enough lines");
}
}
}

我非常感谢这方面的任何帮助。谢谢!

使用字符串拆分,看起来像

try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"));) {
while (fileScanner.hasNextLine()) {
String[] line = fileScanner.nextLine().split("\s+");
if (line.length == 2) {
// Ok, do something
// System.out.println("First: " + line[0] + ", Second: " + line[1]);
} else {
// Wrong
System.out.println("The number of line " + line.length);
}
}
}

最新更新