2014-04-09 45 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()),以便在每次循环迭代开始时不使用令牌。