2013-10-29 3 views
1

우선, 내 코드의 문제가있는 부분은 다음과 같습니다.Java - StringIndexOutOfBoundsException

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

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

그래서, 내가 문제가 여객 클래스에서 생각 :이 매우 기본적인 클래스

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에 있습니다. 수업 시간에 처음으로 수업을 들었을 때 (if (checkPw (password) == true) 부분). 테스트 클래스에서는 매우 명확하게 보이며이 오류가 나타나지 않을 것이라고 생각하지 않습니다. 어떻게이 메시지를 피할 수 있습니까?

전체 오류 :

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) 

자바 결과 : 1

답변

5

문제는 여기에 있습니다 : 당신이 마지막 반복에있을 때

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

, 당신은에 액세스하려는 charstring이고 위치는 i+1이며 존재하지 않습니다. 때문에,

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

for 루프의 마지막 반복에 i5i+1, 또는 6입니다

은 문자열의 끝 떨어져 간다 :

text 
    ^
     | 
when i = 3 charAt(i) will return t and charAt(i+1) will throw the exception 
2

이 줄은 문제가 나타납니다 인덱스의 범위는 0에서 length() - 1입니다. 여기서 해결 방법은 마지막 문자 대신 마지막 두 번째 문자 다음에 반복 반복을 중지하는 것입니다. 변경

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

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

for 루프, 4 인에서 최대 값 i가이 너무 i+1 또는 5 문자열의 마지막을 지나고되지 않도록

합니다.

관련 문제