Call to function fails to return or print
I want to print 10/20 by calling the someFunction function and print first 10 and then 20
class myfirstjavaprog
{
void someFunction(int someParam)
{
System.out.println(someParam);
} <-- error 开发者_Python百科
someFunction(10); <-- error
someFunction(20);
}
I don't understand why it's not working.
You need to put calls to someFunction in their own function, also if you want to call that function without creating an object you'll need to make them static. Also note that it's good java style to make the names of a class start with a capital letter in CamelCase:
public class MyFirstJavaProg {
public static void someFunction(int someParam)
{
System.out.println(someParam);
}
public static void main(String argv[]) {
someFunction(10);
someFunction(20);
}
}
Here's the output:
$ java MyFirstJavaProg
10
20
You need to create a main()
for your java class, and give your method someFunction
static visibility. Try this:
class myfirstjavaprog {
static void someFunction(int someParam) // Note: static visibility
{
System.out.println(someParam);
}
public static void main(final String[] args) // Added main()
{
someFunction(10);
someFunction(20);
}
}
Then you can execute your java class, for example in Eclipse right-click in the source area and select Run as > Java Application
If you didn't give someFunction static visibility, your main would have to instantiate an instance of the class and invoke the method on that, but static is the right choice here, because your method does not need access to any of your class' fields (not that you have any).
精彩评论