我的代码是这样的:
Scanner teclado = new Scanner(System.in);
System.out.println("Rellena con un caracter cada elemento de la primera matriz m1(" + filas1 + "," + cols1 + "), escribe sólo la letra.");
for (int fila = 0; fila < m1.length; fila++) {
for (int col = 0; col < m1[fila].length; col++) {
caracter = teclado.nextLine();
m1[fila][col] = caracter.charAt(0);
}
}
这里给出了一个异常(exception)m1[fila][col] = caracter.charAt(0);
Java.StringIndexOutOfBoundsException
这很奇怪,因为在那之前的行,它不会提示扫描器询问字符串,只是抛出异常,所以我评论了给出异常的行,是的,它提示扫描器询问字符串。
我有点困惑为什么会发生这种情况。
最佳答案
看起来 nextLine()
的结果是空字符串 ""
因此索引 0 处没有字符,因此 charAt(0)
抛出StringIndexOutOfBoundsException
。
如果caracter
是扫描仪,我怀疑您在像nextInt
这样的操作后使用nextLine()
,它不会在之后消耗新行字符用户数据。
Scanner scanner = new Scanner(System.in);
System.out.println("Write some number");
int i = scanner.nextInt();
System.out.println("Write anything");
String data = scanner.nextLine(); // this will not wait for users data
// because it will read data
// before new line mark that user
// passed by pressing enter
System.out.println(i + ">" + data);
要解决此问题,您可以添加 nextLine()
以在 nextInt()
之后使用新行字符。之后,您可以再次使用 nextLine()
并从用户处获取下一个数据。
关于java - 在跳过要求使用 Scanner 输入字符串的行之前出现 StringIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19524428/