Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle StringIndexOutOfBoundsException for string

Tags:

java

try {
    string = scan.nextLine().charAt(0);
} catch(StringIndexOutOfBoundsException siobe){
    System.out.println("invalid input");
}

I am trying to use this code for handling exception for the string that i am getting from a text file. But i get an error saying try to change the actual string declaration to character. I am not sure how to handle this ?

like image 864
Jon Abraham Avatar asked Jan 09 '23 03:01

Jon Abraham


2 Answers

But i get an error saying try to change the actual string declaration to character.

scan.nextLine().charAt(0) is a char so if string is a String (as implied by the compilation error you got), you can't assign a char to it.

If you need just the first character of the input line, you should store it in a char variable.

char first;
try {
    first = scan.nextLine().charAt(0);
} catch(StringIndexOutOfBoundsException siobe){
    System.out.println("invalid input");
}

Of course you can avoid the need to catch this exception if you test the length of the String before getting its first character :

char first;
String line = scan.nextLine();
if (line.length() > 0)
    first = line.charAt(0);
else
    System.out.println("invalid input");
like image 91
Eran Avatar answered Jan 19 '23 13:01

Eran


Your compilation error is because String.charAt() returns a char, not a String. They're different types - and you need to be very clear about the difference between them. You could just change the variable to a char variable, renaming it at the same time - but that's a really bad way of checking whether or not a string is empty. Deliberately provoking an exception like this when you can just test it directly is a bad idea - any time you find yourself catching a specific RuntimeException, you should ask yourself whether there's a better way of avoiding it.

You should use String.isEmpty() or String.length() before trying to take the first character of it. For example:

String line = scan.nextLine();
if (line.isEmpty()) { // Or line.length() == 0
    // Whatever you want to do for invalid input.
} else {
    char firstChar = line.charAt(0);
    // Use firstChar
}

Of course, if you don't actually need the first character, and you were just trying to detect empty strings, you can just use the first part of this, without the else.

like image 45
Jon Skeet Avatar answered Jan 19 '23 13:01

Jon Skeet