1

这个例子演示了使用Scanner逐行读取文件(它不执行写操作)我不知道为什么我尝试编译时会出错。有人可以向我解释原因吗?我正在使用 jcreatorLE 和 JDK 1.6 来运行我的程序:

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

public final class File_read {

  public static void main(String... aArgs) throws FileNotFoundException {
    ReadWithScanner parser = new ReadWithScanner("C:\\Temp\\test.txt");
    parser.processLineByLine();
    log("Done.");
  }

  /**
  * @param aFileName full name of an existing, readable file.
  */
  public ReadWithScanner(String aFileName){
    fFile = new File(aFileName);  
  }

  /** Template method that calls {@link #processLine(String)}.  */
  public final void processLineByLine() throws FileNotFoundException {
    Scanner scanner = new Scanner(fFile);
    try {
      //first use a Scanner to get each line
      while ( scanner.hasNextLine() ){
        processLine( scanner.nextLine() );
      }
    }
    finally {
      //ensure the underlying stream is always closed
      scanner.close();
    }
  }

  /** 
  * Overridable method for processing lines in different ways.
  *  
  * <P>This simple default implementation expects simple name-value pairs, separated by an 
  * '=' sign. Examples of valid input : 
  * <tt>height = 167cm</tt>
  * <tt>mass =  65kg</tt>
  * <tt>disposition =  "grumpy"</tt>
  * <tt>this is the name = this is the value</tt>
  */
  protected void processLine(String aLine){
    //use a second Scanner to parse the content of each line 
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter("=");
    if ( scanner.hasNext() ){
      String name = scanner.next();
      String value = scanner.next();
      log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
    }
    else {
      log("Empty or invalid line. Unable to process.");
    }
    //(no need for finally here, since String is source)
    scanner.close();
  }

  // PRIVATE //
  private final File fFile;

  private static void log(Object aObject){
    System.out.println(String.valueOf(aObject));
  }

  private String quote(String aText){
    String QUOTE = "'";
    return QUOTE + aText + QUOTE;
  }
} 

这是运行它的结果:

--------------------Configuration: <Default>--------------------
C:\Users\administrador\Documents\File_read.java:15: invalid method declaration; return type required
  public ReadWithScanner(String aFileName){
         ^
1 error

Process completed.
4

4 回答 4

6

当您从此处提取该代码时:-),您重命名了类,但没有重命名构造函数。只有构造函数被允许没有返回类型。

我建议您将类重命名或重命名构造函数。

我希望这不是家庭作业。就目前而言,您的教育者将很容易证明抄袭。您至少需要更改变量名和类名,您可能还需要重新格式化它,包括更改类中方法的顺序。

那是如果它是家庭作业。这不是,对吧?:-)

于 2009-04-20T04:07:29.810 回答
3

您的“ReadWithScanner”构造函数需要匹配类的名称(“File_read”)

public File_read(String aFileName){
    fFile = new File(aFileName);  
}
于 2009-04-20T04:06:21.700 回答
1

你的类被命名File_read,你的构造函数被命名ReadWithScanner。警告是您的构造函数需要与类命名相同。

于 2009-04-20T04:07:13.400 回答
0

类的名称是 File_read,因此构造函数名称应该是 File_read,但您将名称命名为 ReadWithScanner,这就是它抱怨的原因。编译器认为它是一个方法名称,因此期望返回类型。

于 2009-04-20T04:05:44.900 回答