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 ?
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
.
See more on this question at Stackoverflow