Java - StringIndexOutOfBoundsException [英] Java - StringIndexOutOfBoundsException

查看:123
本文介绍了Java - StringIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这是我的代码中有问题的部分;这些是非常基本的类

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:

testClass:

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

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

所以,我认为问题出在Passenger类。这是我第一次在课堂上上课(我的意思是if(checkPw(密码)== true)部分)。在测试类中,它看起来非常清晰,我从未想过会出现此错误。如何避免此消息?

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?

完整错误:

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

推荐答案

问题在于:

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

当你进入最后一次迭代时,你'重新尝试在 i + 1 字符串中的 char c $ c>哪个不存在。

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

这篇关于Java - StringIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆