简体   繁体   中英

StringIndexOutOfBoundsException before skipping a line asking to enter a string with Scanner

My code is this one:

    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);
        }
    }

It gives an exception here m1[fila][col] = caracter.charAt(0);

Java.StringIndexOutOfBoundsException

It is curious because the line before that, it doesn't prompt the Scanner asking for a String, just throw the exception, so I commented the line that gives the exception and yes, it prompts the Scanner asking for the String.

I am a bit confused why it is happening.

It seems that result of nextLine() is empty string "" so there is no character at index 0 so charAt(0) throws StringIndexOutOfBoundsException .

If caracter is Scanner them I suspect that you are using nextLine() after operation like nextInt which will not consume new line character after users data.

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);

To solve this problem you can add nextLine() to consume new line character right after your nextInt() . After that you can use nextLine() again and get next data from user.

Take a look here and here for similar questions.

Like Pshemo pointed out, it seems that caracter is equal "". This happens when you just hit Enter in the console and therefor sends an empty line to the scanner. I'm not sure what you are trying to accomplish, but a small check like this should stop that error.

if (!caracter.isEmpty())
    m1[fila][col] = caracter.charAt(0);

Unless you also wants to store when an user sends a new line.

The behavior of scanner.nextLine() is described in the JAVADOC as follows:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

I think you are trying to press an Enter right after execution of System.out.printl(whaever you were doing) . As the documentation suggests trying to insert a new line will be counted as a newLine input omitting the line separator, hence the caracter string will result in an empty string "" .

  caracter = teclado.nextLine(); // press an ENTER
  System.out.println(caracter.equals("")); 
        // it will print true if you press ENTER while it was asking for input 
  m1[fila][col] = caracter.charAt(0); 
        // asking to get index `0` while it is empty!

After immediate execution of System.out.println() try Mouse-clicking on the console to see the caret and insert your input. You will see it is working !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM