Search code examples
javaeclipseruntime-errorterminate

The following code's not running completely


public static void main(String[] args) {
    Scanner xis = new Scanner(System.in);
    System.out.println("Insira o deslocamento desejado.");
    int d = xis.nextInt();
    System.out.println("Digite a mensagem a ser enviada.");
    String m = xis.nextLine();
    for (int i = 0; i < m.length(); i++) 
    {

        int x = m.charAt(i) + d;
        if(x > 'Z')
        {
            System.out.println((char)(x - 26));
        }
        System.out.println((char)x); 
    }

}

That's what the console shows:

Insira o deslocamento desejado.

14 // user's entry

Digite a mensagem a ser enviada.

// After that it says it's been terminated.

I dont understand why it won't run the whole code, is it a problema with the code or with my eclipse?


Solution

  • When you insert the number and hit enter, the call to xis.nextInt() consumes the integer but doesn't consume the next line character. So when you do xis.nextLine(), it reads the next line character and finishes.

    A workaround is to add another call to nextLine() just after nextInt(), like this:

    System.out.println("Insira o deslocamento desejado.");
    int d = xis.nextInt();
    xis.nextLine();
    System.out.println("Digite a mensagem a ser enviada.");
    String m = xis.nextLine();