java - 在跳过要求使用 Scanner 输入字符串的行之前出现 StringIndexOutOfBoundsException

标签 java string java.util.scanner

我的代码是这样的:

    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() 并从用户处获取下一个数据。

看看herehere对于类似的问题。

关于java - 在跳过要求使用 Scanner 输入字符串的行之前出现 StringIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19524428/

相关文章:

java - swing 和 mvc - 监听器的放置位置

python - 正则表达式:排除基于非捕获组的结果?

c++ - 从字符串中提取多个子字符串

string - 为什么 to_ascii_lowercase 返回一个 String 而不是 Cow<str>?

关闭扫描仪时出现 java.util.NoSuchElementException 错误

java - SimpleDateFormat解析

java - 获取异常 java.util.NoSuchElementException : No line found while reading from file?

java - 读取大型文本文件、垃圾收集器和 Scanner 对象的问题

Java 扫描器分隔符检测到 ';',但未检测到 '\n'

java - 我想在运行时更改 SWT 应用程序的语言。怎么做?