最近,在编码时,我遇到了以下错误:
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”开头。
所有变量都已声明,我只是为了保持这篇文章简洁而没有包括它们。