Kristjan Bulič
Kristjan Bulič

Reputation: 58

Why do I get a syntax error on array declaration?

I am new to Java; can someone please explain to me why this gives me an error

Description Resource Path Location Type Syntax error on token ";", { expected after this token InsertionSort.java /Alghoritems/src/sort line 4 Java Problem

package sort;

public class InsertionSort {
    int[] polje = { -2, 5, -14, 35, 16, 3, 25, -100 };
    
    for(int firstUnsorted = 1; firstUnsorted < polje.length; firstUnsorted++) {
        int newElement = polje[firstUnsorted];
        int i;
        for (i = firstUnsorted; i > 0 && polje[i - 1] > newElement; i--) {
            
        }
    }
    
    for (int i = 0; i < polje.length; i++){
        int firstUnsorted = 1;
        int elemant;
        
    }
    

}

Upvotes: 0

Views: 201

Answers (3)

Hamza
Hamza

Reputation: 440

Each Java application needs an entry point, so the compiler knows where to begin executing the application. In the case of Java applications, you need to wrap up your code in the main() method.

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
     }
}

Your code should be

package sort;
    
public class InsertionSort {
    public static void main (String[] args) {
        int[] polje = { -2, 5, -14, 35, 16, 3, 25, -100 };
        
        for(int firstUnsorted = 1; firstUnsorted < polje.length; firstUnsorted++) {
            int newElement = polje[firstUnsorted];
            int i;
            for (i = firstUnsorted; i > 0 && polje[i - 1] > newElement; i--) {
                
            }
        }
        
        for (int i = 0; i < polje.length; i++){
            int firstUnsorted = 1;
            int elemant;
            
        }
        
    }    
}

Upvotes: 1

Renis1235
Renis1235

Reputation: 4690

First of all you have to understand that Java is a programming language that is full on object-oriented. Even when you want to do the simplest thing, you have to create a class with a main method inside. I suggest you start with the basics, before going in for implementations of more difficult algorithms.

package sort;

public class InsertionSort {
   
      public static void main(String[] args)
    {
        int[] polje = { -2, 5, -14, 35, 16, 3, 25, -100 };

        for(int firstUnsorted = 1; firstUnsorted < polje.length; firstUnsorted++) {
            int newElement = polje[firstUnsorted];
            int i;
            for (i = firstUnsorted; i > 0 && polje[i - 1] > newElement; i--) {

            }
        }

        for (int i = 0; i < polje.length; i++){
            int firstUnsorted = 1;
            int elemant;

        }
    }

}

Upvotes: 0

sai
sai

Reputation: 7

Write code in the main method,then the error will not occur.

Upvotes: 1

Related Questions