I am getting this error when I enter the String "s" after entring an integer.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at oneB.change(oneB.java:4)
at oneB.main(oneB.java:26)
Following is the code: (Please note that the code is still complete and I have entered some print statements for checking)
import java.util.Scanner;
public class oneB {
public static String change(int n, String s, String t) {
if (s.charAt(0) == 'R') {
return onetwo(s);
}
return s;
}
private static String onetwo(String one) {
int c = one.indexOf('C');
System.out.print(c);
char[] columnarray = new char[one.length() - c - 1];
for (int i = c + 1; i < one.length(); i++) {
columnarray[i] = one.charAt(i);
}
int columnno = Integer.parseInt(new String(columnarray));
System.out.print(columnno);
return one;
}
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
int n = in .nextInt();
String s = in .nextLine();
String t = in .nextLine();
System.out.print(change(n, s, t));
}
}
It looks like
s
is an empty String""
.You need to start array index from 0. But you are starting from c + 1
Here's how I debugged it:
You are getting a
StringIndexOutOfBoundsException
with index zero at line 4.That means that the String you are operating on when you call
s.charAt(0)
is the empty String.That means that
s = in.nextLine()
is settings
to an empty String.How can that be? Well, what is happening is that the previous
nextInt()
call read an integer, but it left the characters after the integer unconsumed. So yournextLine()
is reading the remainder of the line (up to the end-of-line), removing the newline, and giving you the rest ... which is an empty String.Add an extra
in.readLine()
call before you attempt to read the line intos
.The problem is that when you hit enter, your int is followed by a '\n' character. Just modify the code like this :
The call
in.nextInt()
leaves the endline character in the stream, so the following call toin.nextLine()
results in an empty string. Then you pass an empty string to a function that references its first character and thus you get the exception.One another solution to the problem would be instead of
nextLine()
, use justnext()
.