2014-04-09 44 views
0

我想讀取文本文件並在我的Java程序中打印響應。掃描儀跳過文本文件中的行並不打印前導空格

我的文本文件包含許多行,每行都包含一串等級。其中一些具有領先的空白(表示空白)。

我有兩個問題: 1.文本文件中的第一行不打印;它從第二行開始 2.其中一條等級線在開始處包含兩個「空格」,表示空格;這些空白處不打印。

以下是我的代碼。任何輸入到我如何解決這個問題?這裏的新程序員非常感謝你的幫助。

public static void printResponses (File f) throws FileNotFoundException 
    { 
     Scanner input = new Scanner (f); 
     String line; 
     int count = 1; 

     while (input.nextLine() != null) 
     { 
     line = input.nextLine(); 
     System.out.println ("Student #" + count +"\'s responses: " + line); 
     count++; 
     } 
     System.out.println ("We have reached \"end of file!\"\n"); 

     if (!f.exists()) 
     { 
     System.out.println ("An error occurred. Please try again."); 
     System.exit(0); 
     }                
    } 
+0

請注意,您如何在'while'循環中讀取兩行。 –

+0

'Scanner'類具有'hasNextLine()'方法。 –

+1

另外,'nextLine'永遠不會返回'null'。 –

回答

3

每次通話時間input.nextLine()你從輸入文件耗費了「令牌」。也就是說,Scannerinput會經過您提供的輸入,並在掃描它時「耗盡」一條線。

當您撥打while (input.nextLine() != null)時,您正在使用該文件的第一行。

您想調用while (input.hasNextLine()),以便在每次循環迭代開始時不使用令牌。