简体   繁体   English

如何使用I / O打印带有文件号的txt文件?

[英]How to print txt file with file numbers using I/O?

i am printing a .txt file using the Scanner and I want to print the file with line numbers. 我正在使用Scanner打印.txt文件,并且我想使用行号打印文件。 here is my code. 这是我的代码。 My problem is that the line numbers aren't incrementing. 我的问题是行号没有增加。

import java.util.*;
import java.io.*;


public class List 
{
  public static void main(String[] args) throws IOException
  {
    int line =1;
    File f = new File("src/List.txt");


    Scanner sc = new Scanner(f);
    while(sc.hasNext())
    {
        int num = 1;
        System.out.print(num);
        System.out.println(sc.nextLine());
        num++;
    }
  }
}

Output: 输出:

1Bird
1Dog
1Cat
1Elephant
1Tiger
1Zebra

Expected Output: 预期产量:

1 Bird
2 Dog
3 Cat
4 Elephant
5 Tiger
6 Zebra

Take int num = 1 and place it out side of the loop... int num = 1并将其放在循环的侧面...

int num = 1;
while(sc.hasNext())
{
    System.out.print(num);
    System.out.print(" "); // Separate the line number from the text
    System.out.println(sc.nextLine());
    num++;
}

This way it won't be reset every time the loop restarts... 这样就不会在每次循环重启时都将其重置...

Your bug seems to be mixing up line and num in the body of the loop, but I would also recommend you use formatted output and something like - 您的错误似乎在循环主体中混合了linenum ,但我也建议您使用格式化的输出,例如-

while(sc.hasNextLine()) {
  System.out.printf("%d %s%n", line++, sc.nextLine());
}

The format String "%d %s%n" describes a number then a space then a String and then new-line. String “%d%s%n”的格式表示数字,然后是空格,然后是String ,然后是换行符。 Next, perform a post-increment on line . 接下来,执行后增量line Finally, get the nextLine() from the Scanner . 最后,从Scanner获取nextLine()

You should remove 你应该删除

int num = 1;

because this will ALWAYS set num BACK TO 1 while it hasNext. 因为这将在hasNext时始终将num BACK设置为1。 This is why the line number won't increment. 这就是为什么行号不会增加的原因。

After deleting that, also delete 删除后,也删除

num++;

because there is no more num variable. 因为没有更多的num变量。 Replace that with: 替换为:

line++;

I hope this helps! 我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM