2013-10-29 18 views
1

首先,這裏是我的代碼有問題的部分;這些都是很基本的類Java - StringIndexOutOfBoundsException

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); 
} 

所以,我認爲這個問題是在客運班。這是我第一次在課堂上講課(我的意思是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) 

Java結果:1

回答

5

的問題是在這裏:

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

當你在最後一次迭代的時候,你要訪問charstring的位置i+1不存在。

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

此行似乎是這個問題:

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

當在for循環的最後一次迭代,i5i+1,或6,熄滅了字符串的結尾,因爲指數範圍從0length() - 1。此處的解決方案是在倒數第二個字符而不是最後一個字符後停止for循環迭代。更改

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

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

這樣的最大值i已在for循環是4,所以i+15不脫字符串的結尾。

相關問題