Question

public class createArray {
 public static void main(String args[]){
     int[] Array={1,2,3,4};
     String[] SArray= new String[4];
     SArray[0]="Core";
     SArray[1]=" Java";
     SArray[2]=" Is";
     SArray[3]=" Fun";
     int a=Array[2];

     System.out.println("int[] Array Length Is "+ Array.length +" and numbers are " +Array[0]+Array[1]+a+Array[3]);
     System.out.println(SArray[0]+SArray[1]+SArray[2]+SArray[3]);

     public void compareArray(){}
 }
}

I want to compare two strings but when I am trying to create a method for it, the Java compiler throws a syntax error which says:

Syntax error on token "void"

Was it helpful?

Solution

You can't nest a method within another method

so put public void compareArray(){} outside main method.

class createArray {

public static void main(String args[]) { . . .}///this is a method

public void compareArray() { . . . }///and this is another method 

}///End of the class

OTHER TIPS

You could do something like:

public class createArray {
 public static void main(String args[]){
     int[] Array={1,2,3,4};
     String[] SArray= new String[4];
     SArray[0]="Core";
     SArray[1]=" Java";
     SArray[2]=" Is";
     SArray[3]=" Fun";
     int a=Array[2];

     System.out.println("int[] Array Length Is "+ Array.length +" and numbers are " +Array[0]+Array[1]+a+Array[3]);
     System.out.println(SArray[0]+SArray[1]+SArray[2]+SArray[3]);

     public class InnerClassA{
        public static void compareArray(){ // code here}
     }
 }
}

If it makes sense to use an inner class that is.

public class createArray {
public void compareArray(){
//Give the functionality of compairing two strings here.
}
 public static void main(String args[]){
     int[] Array={1,2,3,4};
     String[] SArray= new String[4];
     SArray[0]="Core";
     SArray[1]=" Java";
     SArray[2]=" Is";
     SArray[3]=" Fun";
     int a=Array[2];

     System.out.println("int[] Array Length Is "+ Array.length +" and numbers are " +Array[0]+Array[1]+a+Array[3]);
     System.out.println(SArray[0]+SArray[1]+SArray[2]+SArray[3]);

//Instantiate your class here and call the method. Somewhat like this:
createArray obj = new createArray();
obj.compareArray(//pass your arrays here);

  }}

You are getting this erro because you have declared a method inside your main method. Hope it helps :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top