0

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ta UVM. I have made sure that the user can enter a string (their name) and the error persists. Here is an example of the program's output:**What is your name?** Sam What is the year of your birth? 1994 What is the date of your birth? (dd.mm) 26.11 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:686)
can you paste youe complete code? and try changin the sequence like this: System.out.println("What is your name?"); junk = sc.nextLine(); userName=sc.nextLine();
I have found the problem. The string userName is indeed empty and the name the user enters is instead stored in junk variable (rather than the enter as I intended). Thanks for the advice for a stupid mistake. @Kirby
0

The call to sc.nextLine() for assigning userName prior to the charAt call likely returns an empty string (eg. if you scan a blank line).

6 Comments

So would you recommend moving the charAt line above userName=sc.nextLine();?
Well, the OP doesn't show how the scanner is initialized, but the point of userName=sc.nextLine() is to retrieve the username, right? Currently, I would bet that sc.nextLine() is returning an empty string, so you're not getting the username you want. In a file, for example, this might happen if you are scanning a newline.
My hunch is that the call to sc.nextLine() is getting a blank token there, so you're not reading the value you want.
Your right about userName=sc.nextLine(). However,this is what the program looks like when it is run: What is your name? Sam What is the year of your birth? 1994 What is the date of your birth? (dd.mm) 26.11 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:148) So the String userName shouldn't be empty.
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.