i am printing a .txt file using the Scanner
and I want to print the file with line numbers. 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;
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 -
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. Next, perform a post-increment on line
. Finally, get the nextLine()
from the Scanner
.
You should remove
int num = 1;
because this will ALWAYS set num BACK TO 1 while it hasNext. This is why the line number won't increment.
After deleting that, also delete
num++;
because there is no more num variable. Replace that with:
line++;
I hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.