我创建了一个程序,该程序应该为Integers读取文本文件并将其放入Arraylist中,然后有很多方法可以对它进行操作。但是,经过一些麻烦的解决之后,我注意到我的程序不会从文本文件中提取整数。有人能指出我正确的方向吗?
package project1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.System;
public class Main {
public static void main(String[] Args) {
Main mainObject = new Main();
mainObject.run();
}
public void run() {
**ArrayList<Integer> list = new ArrayList<>();
String fileName = "p01-in.txt";
Scanner in = new Scanner(fileName);
while (in.hasNextInt()) {
list.add(in.nextInt());
int line = in.nextInt();
System.out.println("%s %n" + line);
}
in.close();**
ArrayList<Integer> listRunsUpCount = new ArrayList<>();
ArrayList<Integer> listRunsDnCount = new ArrayList<>();
Main findRuns = new Main();
listRunsUpCount = findRuns.FindRuns(list, 0);
listRunsDnCount = findRuns.FindRuns(list, 1);
ArrayList<Integer> listRunsCount = new ArrayList<>();
Main mergeRuns = new Main();
listRunsCount = mergeRuns.MergeRuns(listRunsUpCount,
listRunsDnCount);
Main Output = new Main();
Output.Output("p01-runs.txt", listRunsCount);
}
答案 0 :(得分:1)
您可以使用BufferedReader逐行读取文件内容。
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line=reader.readLine();
while (line != null) {
line = reader.readLine();
list.add(Integer.parseInt(line.trim()));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}