请帮助我完成此硬件任务。我应该修改EchoNumber类,该类扩展了Echo类,以便除了显示文本之外还计算文本文件中每行中的字符数。这是Echo类:

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);
  }
}


这是EchoNumber类,请注意它说“您的代码在这里”:

import java.io.*;

public class EchoNumber extends Echo
{

  // the current line number
  private int lineNumber;

  public EchoNumber (String datafile) throws IOException
  {
    super( datafile);
    lineNumber=1;
  }

  // Prints a line with a leading line number and a trailing line length
  // Overrides the processLine method in Echo class
  public void processLine(String line){
    /* your code goes here */
  }
}


这是EchoTester类:

import java.io.*;
import java.util.Scanner;
public class EchoTester
{

  public static void main(String[] args)
  {
    // uses try/catch to handle IOExceptions in main
    try
    {
      String fileName;
      Scanner nameReader = new Scanner(System.in);
      System.out.println("Enter a file name");
      fileName = nameReader.nextLine();
      EchoNumber e = new EchoNumber(fileName);
      e.readLines();
    }
    catch(IOException e)
    {
      e.printStackTrace();
    }
  }
}


最后是.txt文件:

The best things in life are free
A stitch in time saves nine
Still waters run deep
He teaches ill who teaches all
You can not take it with you when you die
Better untaught than ill taught
Do not cross your bridges before you come to them
Soon learnt soon forgotten
Even a worm will turn
It was the last straw that broke the camels back
The way to a mans heart is through his stomach
If the stone fall upon the egg alas for the egg If the egg fall upon the stone alas for     the egg
Where there is a will there is a way
Marry in haste and repent at leisure
One tongue is enough for a woman
If you wish good advice consult an old man
The best advice is found on the pillow
All clouds bring not rain
You can not tell a book by its cover
No news is good news
Bad news travels fast
Live and let live
Birds of a feather flock together
Now is the time
For all good men who actually have the time
To come to the aid of the country in which they live


输出应该是这样的:

1生活中最好的东西是免费的-32

2针及时节省9-27

3静水深21

4他教病,谁教全30

5死后无法随身携带41

6未受教育比受过教病更好31

7来到桥梁之前不要过桥-49

8很快就学会了很快忘记了-26

9这是使骆驼退缩的最后一根稻草48

除非每行之间没有空格。由于某种原因,如果我不分开每一行,它将融合为一个段落。

最佳答案

像这样:

  public void processLine(String line){
    System.out.println(lineNumber + " " + line + "-" + line.length());
    ++lineNumber;
  }


我尚未对其进行测试,因此,如果它不是100%正确,我将保留它作为练习来帮助您完成,但它应该使您走上正确的轨道。祝好运。

09-28 13:59