所以我正在编写一个接受文件输入和文件输出的方法。读取输入文件并在行中添加行号,使其显示为“1 | LINE”,因此数字右对齐3个空格后跟数字和“|”它前后有一个空格。我在打印出线时遇到问题。到目前为止我的代码是:
public class LineNumbers {
public static void process(File input, File output) {
ArrayList<String> fileInput = new ArrayList<String>();
ArrayList<String> out = new ArrayList<String>();
int counter = 0;
int counter1= 1;
try {
Scanner scanner = new Scanner(input);
PrintWriter writer = new PrintWriter(output);
while (scanner.hasNextLine()) {
fileInput.add(scanner.nextLine());
String a = fileInput.get(counter);
String line = String.format("%3s | " ,counter1,a);
out.add(line);
counter++;
counter1++;
for(String n:fileInput){
writer.println(n);
}
}
scanner.close();
writer.close();
} catch (IOException e) {
}
}
}
答案 0 :(得分:1)
你有:
String.format("%3s | " ,counter1,a);
您将a
作为参数传递,但您没有告诉String.format()
该怎么做,所以它什么也没做。
我没有看到与a
对应的格式说明符。你最有可能的意思是:
String.format("%3s | %s" ,counter1,a);
答案 1 :(得分:-1)
根据您的问题,为每行添加行号。以下代码适合您。
public static void process(File input, File output)
{
try
{
Scanner scanner = new Scanner(input);
PrintWriter writer = new PrintWriter(output);
int counter = 1;
while (scanner.hasNextLine())
{
String nextLine = scanner.nextLine();
String line = String.format("%3s | %s", counter, nextLine);
counter++;
writer.println(line);
}
scanner.close();
writer.close();
}
catch (IOException e)
{
}
}