[英]'String Index out of Range' Error Message in Java using charAt
最近,在编码时遇到了以下错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
at java.lang.String.charAt(String.java:686)
at TestAssign2.main(TestAssign2.java:119)
添加行时出现错误firstLetter=userName.charAt(0);
用户输入所有要求的值后,代码和程序中的会显示错误消息。 在输入此行之前,一切正常。
while(uProgStart.equals(PROGSTART))
{
System.out.println("What is your name?");
userName=sc.nextLine();
junk = sc.nextLine();
System.out.println("What is the year of your birth?");
birthYear = sc.nextInt();
junk = sc.nextLine();
System.out.println("What is the date of your birth? (dd.mm)");
birthDDMM = sc.nextDouble();
junk = sc.nextLine();
day=(int)birthDDMM;
month=(int)Math.round(100*birthDDMM)%100;
//Begins calculation of Dss Score
if(birthYear%CYCLE_LENGTH!=SNAKE_YEAR)
{
DssScore=DssScore+1;
}
if(month<SPRING_BEGINNING||month>SPRING_END)
{
DssScore=DssScore+2;
}
firstLetter=userName.charAt(0);
if(firstLetter==(LOWER_S)||firstLetter==(UPPER_S))
{
DssScore=DssScore+4;
}
该行的目的是查看用户输入的名称是否以字母“ s”或“ S”开头。
所有变量都已声明,为使本文简洁一些,我只是未将它们包括在内。
我认为您是在错误地按Enter键而没有机会输入任何输入,并且这迫使用户名变量为空。 我如上所述重现了此错误。有时当您使用scanner
,会发生这种情况。
因此,在执行任何操作之前,请在代码中检查username
是否为null。
在charAt调用之前,对sc.nextLine()
的调用sc.nextLine()
用于分配userName
sc.nextLine()
可能返回一个空字符串(例如,如果您扫描空白行)。
您可能要使用if
要确保下一行确实存在。
像这样:
if(sc.hasNextLine()) {
userName = sc.nextLine()
} else {
System.out.println("OMG... Where is my line?")
}
这很可能不能很好地解决您的问题,但是基于有限的信息,我们很难提出更好的建议。
真正的问题很可能是您逻辑中的其他地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.