本文介绍了StringIndexOutOfBoundsException字符串索引超出范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输入整数后输入字符串"s"时出现此错误.
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));
}
}
推荐答案
调用in.nextInt()
将结束符留在流中,因此以下对in.nextLine()
的调用将导致一个空字符串.然后,将空字符串传递给引用其第一个字符的函数,从而获得异常.
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.
这篇关于StringIndexOutOfBoundsException字符串索引超出范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!