i know scan.nextline() gives a character
No, it gives a string.
So is there anyway to handle an exception in such a way that i am able to manage to keep string after scan.nextline().
The real problem is that you are not handling the case where nextLine()
returns an empty string. You cannot retrieve characters from an empty string – there is no characters present!
String x = scan.nextLine();
if (!x.isEmpty()) { // <-- add this
char ch = x.charAt(0);
// use ch as needed...
}
else {
// do something else ...
}
If you must have the char
as a string
, you can do this:
char ch = x.charAt(0);
string s = String.valueOf(ch);
Or this:
string s = x.substring(0, 1);
Update:
while (scan.hasNext()) {
String x = scan.nextLine();
String s;
if (!x.isEmpty()) { // <-- here
s = x.substring(0,1);
} else {
s = "";
}
// use s as needed...
}
5
solved Stringoutofboundexception for string