简体   繁体   中英

'String Index out of Range' Error Message in Java using charAt

Recently, while coding I came upon the following error:

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)

The error appears when I add the line - firstLetter=userName.charAt(0); to the code and program displays the error message after the user enters all the values asked. Before this line was entered, it all worked fine.

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

The idea of the line was to see if the name entered by the user begins with either the letter 's' or 'S'.

All the variables have been declared, I just haven't included them for the sake of keeping this post a little succinct.

I think you are pressing enter key by mistake without giving a chance to enter any input and it forces username variable be empty. I reproduced this error like mentioned above.Sometime when you deal with scanner , it happens like that.

So in your code, check whether the username is null or not before doing any operation.

在charAt调用之前,对sc.nextLine()的调用sc.nextLine()用于分配userName sc.nextLine()可能返回一个空字符串(例如,如果您扫描空白行)。

You may want to use if to make sure that the next line really exists.

Something like this:

if(sc.hasNextLine()) {
   userName = sc.nextLine()
} else {
  System.out.println("OMG... Where is my line?")
}

This most likely not a good fix for your problem, but based on the limited information we have it's difficult to suggest anything better.

The real problem is most likely elsewhere in your logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM