我慢慢地,但肯定通过java工作,并得到一个程序工作.但是,我使用的程序包含main方法中的所有代码,我想使用其他方法来保持更好的组织.
我的问题非常简单,所以我将使用最简单的例子.说我想创建一个这样的Hello World程序:
public class HelloWorld {
public static void main(String[] args) {
Test();
}
public void Test(){
System.out.println("Hello World!");
}
}
Run Code Online (Sandbox Code Playgroud)
如何在java中正确调用Test()?我写它的方式会产生编译错误.我来自R,这将允许这样的事情.
谢谢.
首先,应该命名您的方法test(而不是"测试").此外,它应该是(在这种情况下)static.
public static void main(String[] args) {
test();
}
public static void test(){
System.out.println("Hello World!");
}
Run Code Online (Sandbox Code Playgroud)
或者,您也可以这样写,
public static void main(String[] args) {
new HelloWorld().test(); // Need an instance of HelloWorld to call test on.
}
public void test() { //<-- not a static method.
System.out.println("Hello World!");
}
Run Code Online (Sandbox Code Playgroud)