user1489540
user1489540

Reputation:

ArrayIndexOutOfBoundsException while implementing Sieve of Eratosthenes

When I run my program I get the following exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
        at eraKevgiri.main(eraKevgiri.java:29)

What is the problem with this code?

public static void main(String[] args) {
    int gSayi = 0;
    int kKok = (int) Math.sqrt(gSayi);
    boolean[] liste = new boolean[gSayi + 1];

    Scanner klavye = new Scanner(System.in);
    System.out.println("Sayı Girin:");
    gSayi = klavye.nextInt();

    for(int i=2; i<=kKok; i++){
        System.out.println("" +i);
        for(int j=i*i; j<=gSayi; j+=i){
            liste[j] = true;
        }
    }

    for(int k=kKok; k<=gSayi; k++){ 
        if(!liste[k]){ //-------> problem in here
            System.out.println("" + k);
        }
    }
    klavye.close();
}

Upvotes: 1

Views: 151

Answers (4)

Kim Stebel
Kim Stebel

Reputation: 42047

You should move

Scanner klavye = new Scanner(System.in);
System.out.println("Sayı Girin:");
gSayi = klavye.nextInt();

to the beginning of the method, otherwise the array will always have only one element and then of course there is no element with index 1.

Upvotes: 2

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41220

for(int k=kKok; k<=gSayi; k++) here gSayi's value is taken from user. So if it greater than 1 then it raise a error as boolean[] liste size is 1.That is why liste[k] goes out of bound.

you should make liste this to dynamic, ex List.

Upvotes: 0

Brian
Brian

Reputation: 17319

You're doing things in the wrong order. When you call:

boolean[] liste = new boolean[gSayi + 1];

You're creating an array with only one element since gSayi + 1 is always 1 here. Move your code around like this:

Scanner klavye = new Scanner(System.in);
System.out.println("Sayı Girin:");
int gSayi = 0;
gSayi = klavye.nextInt();
int kKok = (int) Math.sqrt(gSayi);
boolean[] liste = new boolean[gSayi + 1];

The size of the array won't change because you update gSayi. Likewise with kKok, it won't be updated to the new square root of gSayi. It will use the value at that instance of time.

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

You first allocate an array of size gSayi + 1, which is 0 + 1 = 1. Later, you modify gSayi and try to access an element of liste, which has just one element.

So, you must either not modify gSayi or adjust your array to the modified value.

Upvotes: 1

Related Questions