2016-10-26 45 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