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. 

但我正在尝试编辑 EchoDouble 类中的 processLine 方法,以便它将像这样以双倍行距回显文本文件

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中这个回声和扫描仪的新手,并且被困在这个问题上。如果有人可以就如何解决这个问题给我任何建议,将不胜感激!

4

3 回答 3

2

这个怎么样:

@Override
public void processLine(String line){
     System.out.println(line);
     System.out.println();
}
于 2013-04-10T22:33:39.940 回答
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

于 2013-04-10T22:35:27.143 回答
1

做:

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

\n 是创建新行的原因,然后它会回显。

于 2013-04-11T11:57:48.220 回答