2014-09-04 58 views
1

我正在使用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 
+1

您正在重新創建int num = 1;每個循環迭代。 將聲明int num = 1放到循環外部並且所有內容都應該正常工作 – nem035 2014-09-04 02:16:49

回答

4

採取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++; 
} 

這樣,它贏得了每次都不會重置循環重新開始......

+1

也可以像這樣添加單個空格字符串System.out.print(num +「」);'來分隔數字和單詞。 (*以外) – 2014-09-04 02:00:44

+0

@ t.pimentel良好的建議;) – MadProgrammer 2014-09-04 02:03:32

0

您應該刪除

int num = 1; 

,因爲這將始終設置NUM回到1,而它hasNext。這就是行號不會增加的原因。

刪除在此之後,也刪除

num++; 

,因爲沒有更多的num變量。將其替換爲:

line++; 

我希望這有助於!

2

你的錯誤似乎在循環體被混合起來linenum,但我也建議你使用格式化輸出和喜歡的東西 -

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

格式String「%d%S% n「表示一個數字,然後是空格,然後是String,然後是新行。接下來,在line上執行後期增量。最後,從Scanner獲取nextLine()