Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid StringIndexOutOfBoundsException when char has no value?

Tags:

java

null

char

Sorry if the title made no sense but I did not know how to word it.

The problem:

I'm making a multiple choice quiz game that gets either a, b, c or d from the user. This is no problem if they do as they are told, however if they don't type anything and just hit enter I get a StringIndexOutOfBoundsException. I understand why this is happening, but I'm new to Java and can't think of a way to fix it.

What I have so far:

    System.out.println("Enter the Answer.");

    response = input.nextLine().charAt(0);

    if(response == 'a')
    {
            System.out.println("Correct");
    }

    else if(response == 'b' || response == 'c' || response == 'd')
    {
        System.out.println("Wrong");
    }
    else
    {
        System.out.println("Invalid");
    }

Of course the program will never make it past the second line of code if the user types nothing, because you can't take the charAt(0) value of an empty String. What I'm looking for is something that will check if the response is null, and if so ask go back and ask the question to the user again.

Thanks in advance for any answers.

like image 924
hashtag name Avatar asked Oct 22 '12 03:10

hashtag name


2 Answers

You can use a do-while loop. Just replace

response = input.nextLine().charAt(0);

with

String line;

do {
  line = input.nextLine();
} while (line.length() < 1);

response = line.charAt(0);

This will continue to call input.nextLine() as many times as the user enters a blank line, but as soon as they enter a non-blank line it will continue and set response equal to the first character of that non-blank line. If you want to re-prompt the user for the answer, then you could add the prompt to the inside of the loop. If you want to check that the user entered a letter a–d you could also add that logic to the loop condition.

like image 78
DaoWen Avatar answered Sep 22 '22 21:09

DaoWen


Either handle the exception(StringIndexOutOfBoundsException) or break this statement

    response = input.nextLine().charAt(0);

as

    String line = input.nextLine();
    if(line.length()>0){
        response = line.charAt(0);
    }

Exception Handling:

    try{
        response = input.nextLine().charAt(0);
    }catch(StringIndexOutOfBoundsException siobe){
        System.out.println("invalid input");
    }
like image 31
Yogendra Singh Avatar answered Sep 21 '22 21:09

Yogendra Singh