我已经创建了一个方法,但Java没有看到它 - Java

时间:2015-03-17 03:34:28

标签: java

我一直在TheNewBoston学习编程一段时间,而在第80个教程中我正在编写文件。我逐字逐句地遵循他的代码,但是eclipse说该方法未定义为类型" creatfile"。我一遍又一遍地检查,但我无法看到问题。这是代码。

creatfile.java

import java.util.Formatter;

public class creatfile {

private Formatter x;

public void openFile(){
    try{
        x = new Formatter("chinese.txt");
    }
    catch(Exception e){
        System.out.println("you have an error");
    }

public void addRecords() { //there is an error on "void" and "addRecords"
    x.format("%s%s%s", "20 ", "Jacob ", " Peterson");
}
public void closeFile(){ //error here to
    x.close();
    }
  }
}

apple.java(我的主要课程)

import java.util.*;

public class apples {
    public static void main(String[] args) {
        creatfile g =  new creatfile() {
            g.openFile();
            g.addRecords();
            g.closeFile();
        }
    }
}

3 个答案:

答案 0 :(得分:5)

你错过了openFile() {

定义中的右大括号
public void openFile(){
    try{
        x = new Formatter("chinese.txt");
    }
    catch(Exception e){
        System.out.println("you have an error");
        e.printStackTrace(); // <-- don't just say an error.
    }
} // <-- Add this.

答案 1 :(得分:1)

变化:

creatfile g =  new creatfile() {
            g.openFile();
            g.addRecords();
            g.closeFile();
        }

到此:

creatfile g =  new creatfile();
g.openFile();
g.addRecords();
g.closeFile();

答案 2 :(得分:1)

您的main方法没有意义。试试这个:

public class apples {
    public static void main(String[] args) {
        creatfile g =  new creatfile();
        g.openFile();
        g.addRecords();
        g.closeFile();
    }
}