2016-10-26 44 views
2

首先,让我写序言:我正在编写一个程序,它允许我带三个文件,每个文件包含一段圣经经文的不同译文,并计算出数字字,行和字符。我的一个问题是,文件的第一行仅包含特定翻译的版本(即KJV)。我想让它开始运行,同时跳过文件的第一行。需要只从第二行读取

到目前为止,我有我的代码是这样的:

import java.util.*; 
import java.io.*; 

public class Assign6 
{ 
    public static void main(String[]args) throws Exception{ 

     int wordCount = 0; 
     int lineCount = 0; 
     int charCount = 0; 
     java.io.File file1 = new java.io.File("translation1.txt"); 
     java.io.File file2 = new java.io.File("translation2.txt"); 
     java.io.File file3 = new java.io.File("translation3.txt"); 
     java.io.PrintWriter file4 = new java.io.PrintWriter("CompareInfo.txt"); 
     Scanner input = new Scanner(file1); 
     Scanner input2 = new Scanner(file2); 
     Scanner input3 = new Scanner(file3); 


     while(input.hasNextLine()){ 

       String line = input.nextLine(); 

       lineCount++; 

       String str[] = line.split((" ")); 
         for(int i = 0; i <str.length; i++){ 
          wordCount++; 
         } 
         charCount += (line.length()); 

       } 
       file4.println("In the King James, there are " + lineCount + " Lines, " + wordCount + " Words, and " + charCount + " Characters."); 
       lineCount = 0; 
       charCount = 0; 
       wordCount = 0; 

       while(input2.hasNextLine()){ 

       String line = input2.nextLine(); 

       lineCount++; 

       String str[] = line.split((" ")); 
         for(int i = 0; i <str.length; i++){ 
          wordCount++; 
         } 
         charCount += (line.length()); 

       } 
       file4.println("In the NIV, there are " + lineCount + " Lines, " + wordCount + " Words, and " + charCount + " Characters."); 

       lineCount = 0; 
       wordCount = 0; 
       charCount = 0; 

       while(input3.hasNextLine()){ 

       String line = input3.nextLine(); 

       lineCount++; 

       String str[] = line.split((" ")); 
         for(int i = 0; i <str.length; i++){ 
          wordCount++; 
         } 
         charCount += (line.length()); 

       } 
       file4.println("In the Message, there are " + lineCount + " Lines, " + wordCount + " Words, and " + charCount + " Characters."); 

    file4.close(); 
    System.out.println("File written.");  
    } 
}  

你以为if语句会的工作,我只是增加了一次,如果它是文本文件,如果是这样的第一线我究竟该怎么做呢?

+2

在循环之前添加一个'input.nextLine();'。为了安全起见,确保首先有一条线。 –

+0

只需在while循环前工作 – arop

回答

0

在循环其他行之前读取一行一次?像:

Scanner input = new Scanner(file1); 
Scanner input2 = new Scanner(file2); 
Scanner input3 = new Scanner(file3); 

input.nextLine(); 
input2.nextLine(); 
input3.nextLine(); 

while(input.hasNextLine()){ 
//etc 

所以它只是跳过他们,因为读者已经看过一次。

+0

就可以调用input.nextLine(),这对于让我回到正确的轨道确实很有帮助,但是我稍微玩了一下,并且它不是我需要的hasNextLine,但是我只需要使用input.nextLine()来跳过第一行。 –

+0

@JacobPorter对,在睡觉前我写了这个答案,所以我犯了一个严重的错误。现在编辑它。 – Voltboyy