2013-04-10 12 views
2

我必須創建一個EchoDouble類,它將Echo類的響應文本文件擴展到控制檯。用掃描儀回顯文本文件並讓它雙倍間隔?

該說的文本文件的內容是

Nature's first green is gold, 
Her hardest hue to hold. 
Her early leaf's a flower; 
But only so an hour. 

但我試圖編輯ProcessLine從方法在EchoDouble類,以便它會回顯雙倍行距這樣

Nature's first green is gold, 

Her hardest hue to hold. 

Her early leaf's a flower; 

But only so an hour. 
文本文件

回聲類

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

    public class Echo{ 
     String fileName; // external file name 
     Scanner scan; // Scanner object for reading from external file 

     public Echo(String f) throws IOException 
     { 
     fileName = f; 
     scan = new Scanner(new FileReader(fileName)); 
     } 

     // reads lines, hands each to processLine 
     public void readLines(){ 
     while(scan.hasNext()){ 
      processLine(scan.nextLine()); 
     } 
     scan.close(); 
     } 

     // does the real processing work 
     public void processLine(String line){ 
     System.out.println(line); 
     } 
    } 

EchoDouble類

import java.io.*; 

public class EchoDouble extends Echo 
{ 
    public EchoDouble (String datafile) throws IOException 
    { 
    super(datafile); 
    } 

    // Prints the given line and inserts a blank line 
    // Overrides the processLine method in Echo class 
    public void processLine(String line) 
    { 
    /* **code here** */ 
    } 
} 

我是新來此呼應,掃描儀在Java和我堅持這個問題。如果任何人都可以給我任何建議如何解決這個問題,將不勝感激!

回答

2

如何:

@Override 
public void processLine(String line){ 
    System.out.println(line); 
    System.out.println(); 
} 
+1

哇,這是如此簡單,不知道爲什麼我沒有想到這一點!非常感謝! – aiuna 2013-04-10 22:35:34

+0

@aiuna歡迎您! – informatik01 2013-04-10 22:39:43

2

做最簡單的事情是:

public void processLine(String line) { 
    System.out.println(line); 
    System.out.println(); 
} 

但是,這將使你在最後一個額外的空行。或者,

public void processLine(String line) { 
    System.out.println(); 
    System.out.println(line); 
} 

會在開始時給您一個額外的空行。所以你需要一個概念,看它是否是第一行。

你可以把這些知識在processLine

private boolean printedAnythingYet = false; 
public void processLine(String line) { 
    if (printedAnythingYet) { 
    System.out.println(); 
    } 
    System.out.println(line); 
    printedAnythingYet = true; 
} 

或者在您的readLines

public void readLines() { 
    boolean isFirstLine = true; 
    while (scan.hasNext()) { 
    processLine(scan.nextLine(), isFirstLine); 
    isFirstLine = false; 
    } 
    scan.close(); 
} 

public void processLine(String line, boolean isFirstLine) { 
    if (!isFirstLine) { 
    System.out.println(); 
    } 
    System.out.println(line); 
} 

我不知道其中哪些我更喜歡。說實話,我不認爲processLine應該是public

+0

謝謝,我會牢記以備將來使用! – aiuna 2013-04-10 22:36:48

1

做:

public void processLine(String line){ 
    System.out.println("\n" + line); 
} 

的\ n是什麼創造一個新的生產線,那麼它相呼應。