this is a very simple program. I have created a new class, and I ami going to define a new method to recall next in a new class.
public class MyClass {
public static void main(String[] args) {
int number = 1;
public void showSomething(){
System.out.println("This is my method "+number+" created by me.");
}
}
}
But, when I run this program I encounter an error:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token(s), misplaced construct(s)
Syntax error on token "void", @ expected
-
6showSomething() need to be defined outside of main()Rick S– Rick S2014年11月25日 15:36:34 +00:00Commented Nov 25, 2014 at 15:36
-
What do you want the code to do? You've got a method inside another method. Why?Silvio Mayolo– Silvio Mayolo2014年11月25日 15:36:38 +00:00Commented Nov 25, 2014 at 15:36
6 Answers 6
Error is because you are declaring a method inside another method here it is main().
change this:
public static void main(String[] args) {
int number = 1;
public void showSomething(){
System.out.println("This is my method "+number+" created by me.");
}
}
to
public static void main(String[] args) {
int number = 1;
showSomething(); // call the method showSomething()
}
public static void showSomething(){
System.out.println("This is my method "+number+" created by me.");
}
Also showSomething() should be declared static since main() is static. Only static methods can be called from another static method.
1 Comment
You cannot declare a method into a method.
Do it like this :
public class MyClass {
public static void main(String[] args) {
int number = 1;
showSomething(number);
}
public static void showSomething(int number){
System.out.println("This is my method "+number+" created by me.");
}
}
Comments
public class MyClass {
public static void main(String[] args) {
new MyClass().showSomething();
}
public void showSomething(){
int number = 1;
System.out.println("This is my method "+number+" created by me.");
}
}
Comments
Should be like this (define the method outside the main),
public class MyClass {
public static void showSomething(int number){
System.out.println("This is my method "+number+" created by me.");
}
public static void main(String[] args) {
int number = 1;
showSomething(number);
}
}
Comments
You can't create a method inside your main. Instead do like this:
public class MyClass {
public static void main(String[] args) {
showSomething();//this calls showSomething
}
public void showSomething(){
int number = 1;
System.out.println("This is my method "+number+" created by me.");
}
}
In your class you have a main method that runs the program. On the same level you have the other methods or variables you want to use in the program.
Comments
public class MyClass {
public static void main(String[] args) {
int number = 1;
showSomething(number
}
public void showSomething(int number){
System.out.println("This is my method "+number+" created by me.");
}
}