0

So I'm fairly new to programming, and I'm working on a simple practice program that finds a letters order in the alphabet. This should have been pretty easy...but for some reason I get a StringIndexOutOfBoundsException when I add a while loop. So the program does do what it should the first time...but will not allow me to test again with out re-running the program. I tested the while loop with nothing but a simple print statement inside and it worked, so I'm confused as to why the while loop isn't working with my alphabet program.

Any help would be greatly appreciated thanks!

import java.io.*;
public class test {


    public static void main(String[] args) throws IOException 
    {
        BufferedReader in;
        in = new BufferedReader (new InputStreamReader (System.in));
        boolean again=true;
        String response;

        while (again)
        {

            System.out.println("Enter a letter to find it's order in the alphabet");

            char theLetter = (char) in.read();

            System.out.println(theLetter + " is the " + convertLetter(theLetter) + "th letter of the alphabet");

            System.out.println("want to play again?");

            response = in.readLine();

            if (response.charAt(0)=='n')
            {
                again=false;
            }
        }

        System.out.println("end program");
    }


    public static int convertLetter(char TheLetter)
    {
        //number value 'a'=97
        //number value 'b'=98
        //number value 'c'=99

        //subtracting 'a' from any other number will reveal how many places away that number is from the start
        //thus finding it's chronological place in the alphabet

        int NumberValue= (int)TheLetter;
        int a = 'a';

        int CalulateOrder = (NumberValue - a) + 1; 

        return CalulateOrder;

    }
}
3
  • 1
    What line does the exception occur at? Commented Jul 12, 2012 at 18:49
  • line 25 seems to be the problem Commented Jul 12, 2012 at 18:50
  • @ThisBetterWork please mark it more precisely. Commented Jul 12, 2012 at 18:51

6 Answers 6

3

When you hit enter for the original char, that newline is still in the buffer since you only call read() and only get 1 character, leaving the newline in the buffer from hitting enter. So when you call readLine it simply hits that newline and returns an empty string.

You can test this by typing something with more than one character when it first asks you for a character, and it will go for a second loop since the readLine will return a non-empty string.

To fix this change your original read() to readLine() so that it gets the newline caused from you hitting enter, then just grab the first character from the string.

This should fix it:

    import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {
        BufferedReader in;
        in = new BufferedReader (new InputStreamReader (System.in));
        boolean again=true;
        String response;

        while (again) {
            System.out.println("Enter a letter to find it's order in the alphabet");
            response = in.readLine();
            if (response.length() > 0) {
                char theLetter = response.charAt(0);

                System.out.println(theLetter + " is the " + convertLetter(theLetter) + "th letter of the alphabet");
                System.out.println("want to play again?");

                response = in.readLine();
                if (response.length() > 0 && response.charAt(0)=='n') {
                    again=false;
                }
            }
        }
        System.out.println("end program");
    }

    public static int convertLetter(char TheLetter) {
        return (TheLetter - 'a') + 1;
    }

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

2 Comments

ok, I see what's going on now. I normally don't use read(), but eclipse suggested it would allow me read in a character when readLine() would not....but really I just needed .charAt(0) at the end of readLine. Thanks for your help. :)
@NominSim Edited to prevent exceptions caused by just hitting enter
3
 if (response.charAt(0)=='n') 

If the String is empty "", there will be no character at position 0. Check for it before doing charAt()

3 Comments

because String response is set to read in from the keyboard....I thought the program would stop at that point and wait for a response to be entered....why is it just bypassing that line?
It stops, but if you just hit enter it returns the empty string
You're left with an extra newline in the buffer from the original character. If you type "a" and hit enter, there is "a\n" in the buffer. read() simply reads a char, so there is still a newline in te buffer, so when you call readLine(), which reads until a newline, it returns an empty string rather than blocking for input.
1

is the length of response null or ""? if it is you will not be able to get the char at index 0

Comments

1

I bet the culprit is that you're hitting "enter" at the want to play again? prompt. The in.readLine(); returns the line without the trailing newline (see the javadocs), which means that if you only press "enter" it will return an empty string, thus the StringOutOfBoundException while checking the first char.

Check for the empty string before checking for the char:

if(response.length() > 0 && response.charAt(0) == 'n')

1 Comment

yes, I think you're right. That makes sense. thank you :) edit:although I'm not hitting enter right after that prompt....so I think it's actually maybe from hitting enter before.
1

The only place you access a string index is at if (response.charAt(0) == 'n') so that is most likely your problem area.

if(response.length() > 0 && response.charAt(0) == 'n')

Should do the trick.

Edit: As @TreySchroeder points out, there is another problem with your program, in that you don't read the full line at first. Put in.readLine(); after your initial theLetter = (char) in.read();, and use this fix for the other issue.

1 Comment

While this will prevent an exception from being thrown, it does not solve the actual problem.
0
if (response.isEmpty() && response.charAt(0)=='n')

will avoid the exception.

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.