调用main方法

时间:2016-03-11 08:12:54

标签: java

我在文件上使用 bufferedwriter 并完成了我的代码。但我的问题是将其称为主要方法。我该怎么办?这是方法的名称:

public void writerof(final String filePath, final int n) throws IOException.....

所以在主要方法中我会说:

writerof("file.txt", 6)

我在writeof部分出现错误,它表示writeof未定义。

这些也是我的最后一块:

    catch (IOException ioe) {

        ioe.printStackTrace();

    }


    finally {

        if (writer != null) writer.close();
    }

    }

有任何错误吗?

3 个答案:

答案 0 :(得分:6)

将其设为静态,如:

public static void main(String[] args) {
        try {
            writerof("file.txt", 6);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writerof(final String filePath, final int n) throws IOException {
        System.out.println("my method here");
    }

或者可能更好一点:

public static void main(String[] args) {

        MyClass z = new MyClass();
        try {
            z.writerof("file.txt", 6);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public  void writerof(final String filePath, final int n) throws IOException {
        System.out.println("my method here");
    }

答案 1 :(得分:3)

由于您的方法签名表明它不是static,而我们的mainstatic method所以它无法调用它。 因此,要么staticmain中创建该类的对象,请调用它。

答案 2 :(得分:1)

您的代码中有2个问题(如果我已正确使用):

  • 第一个问题 - 在静态上下文中调用对象的方法。您需要将此方法设为静态或创建此类的对象并调用这些对象的此方法。
  • 第二个问题 - 你调用抛出异常的方法,而我不确定你是不是从main方法抛出它(你应该从main方法抛出它或用try-catch块环绕它)。
相关问题