1

First of all, here is the problematic part of my code; these are very basic classes

public Passenger(String Name, String adress, String number, String password){
    count++;
    accId+=count;

    this.Name=Name;

    this.adress=adress;
    this.number=number;

    if(checkPw(password)==true){
        this.password=password;
    }

}

private boolean checkPw(String password){
    int length;
    length = password.length();

    if(length != 6){
        return false;
    }
    else if(password.charAt(0)==0){
        return false;
    }
    else {
        for (int i = 0; i < password.length();i++){
            if((password.charAt(i))==(password.charAt(i+1))){
                return false;
            }
        }
    }
    return true;        
}

testClass:

public static void main(String[] args){
    Passenger gokhan=new Passenger("Gokhan","Istanbul","xxx","254651");

    System.out.println(gokhan.password);
}

So, I think the problem is in the Passenger class. Its my first time that class in class things (I meant the if(checkPw(password)==true) part). In the test class, it looks very clear and I never thought that this error will appear. How can I avoid this message?

Full error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
    at java.lang.String.charAt(String.java:658)
    at project1.Passenger.checkPw(Passenger.java:45)
    at project1.Passenger.<init>(Passenger.java:27)
    at project1.testClass.main(testClass.java:11)

Java Result: 1

0

2 Answers 2

5

The problem is here :

for (int i = 0; i < password.length();i++){
    if((password.charAt(i))==(password.charAt(i+1))){
        return false;
    }
 }

When you're in the last iteration, you're trying to access the char in the string at the position i+1 which doesn't exists.

    text
       ^
       |
when i = 3 charAt(i) will return t and charAt(i+1) will throw the exception
Sign up to request clarification or add additional context in comments.

Comments

2

This line appears to be the problem:

if((password.charAt(i))==(password.charAt(i+1))){

When on the last iteration of the for loop, i is 5 and i+1, or 6, goes off the end of the string, because indexes range from 0 to length() - 1. The solution here is to stop the for loop iteration after the second-to-last character instead of the last character. Change

for (int i = 0; i < password.length();i++){

to

for (int i = 0; i < password.length() - 1; i++){

So that the maximum value i has in the for loop is 4, so i+1 or 5 isn't off the end of the string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.