我正在使用Scanner
打印.txt文件,我想用行號打印文件。這是我的代碼。我的問題是行號不增加。如何使用I/O打印帶有文件編號的txt文件?
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++;
}
}
}
輸出:
1Bird
1Dog
1Cat
1Elephant
1Tiger
1Zebra
預期輸出:
1 Bird
2 Dog
3 Cat
4 Elephant
5 Tiger
6 Zebra
您正在重新創建int num = 1;每個循環迭代。 將聲明int num = 1放到循環外部並且所有內容都應該正常工作 – nem035 2014-09-04 02:16:49