首先,这是我的代码有问题的部分;这些是非常基础的课程
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;
}
测试类:
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