简体   繁体   中英

Why does java.lang.ArrayIndexOutOfBoundsException happen on this piece of code?

public boolean felGissningar(char gi, int antalfel){
    if(antalfel>0){
    int test = 0;
    for (int i = 0; i<felGiss1.length; i++){
        if(gi == felGiss1[i]){
            test+=1;
        }
    }
    felGiss2 = new char[antalfel];
    for (int i = 0; i<felGiss1.length; i++){
        felGiss2[i]=felGiss1[i];
    }

    felGiss1 = new char[antalfel+1];
    for (int i =0;i<antalfel; i++){
        felGiss1[i]=felGiss2[i];
    }
    felGiss1[antalfel] = gi;
    System.out.println("1: "+String.valueOf(felGiss1));
    System.out.println("2: "+String.valueOf(felGiss2));
    if(test>0){
        return false;
    } else {
        return true;
    }
    }else {
        felGiss1 = new char[1];
        felGiss1[0]=gi;
        return true;
    }
}

antalfel means number of incorrect answers

After this boolean has returned false once it says java.lang.ArrayIndexOutOfBoundsException

what im trying to do is to not allow for the same wrong character twise.

Over here:

    felGiss2 = new char[antalfel];
    for (int i = 0; i<felGiss1.length; i++){
        felGiss2[i]=felGiss1[i];
    }

Since you didn't post where felGiss1 was created, if felGiss1.length is greater than felGiss2.length then it will produce an exception. Please change to:

    felGiss2 = new char[antalfel];
    for (int i = 0; i<felGiss1.length && i < fellGiss2.length; i++){
        felGiss2[i]=felGiss1[i];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM