问题
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));
}
}
回答1:
The call in.nextInt()
leaves the endline character in the stream, so the following call to in.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.
回答2:
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 your nextLine()
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 into s
.
回答3:
One another solution to the problem would be instead of nextLine()
, use just next()
.
int n = in .nextInt();
String s = in .next();
回答4:
It looks like s
is an empty String ""
.
回答5:
for (int i = c + 1; i < one.length(); i++) {
columnarray[i] = one.charAt(i); // problem is here.
}
You need to start array index from 0. But you are starting from c + 1
for (int i = c + 1,j=0; i < one.length(); i++,j++) {
columnarray[j] = one.charAt(i);
}
回答6:
The problem is that when you hit enter, your int is followed by a '\n' character. Just modify the code like this :
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
int n = in .nextInt();
in.nextLine(); //This line consume the /n afer nextInt
String s = in .nextLine();
String t = in .nextLine();
System.out.print(change(n, s, t));
}
来源:https://stackoverflow.com/questions/18916959/stringindexoutofboundsexception-string-index-out-of-range-error