0

So I am trying to let the user input a message and an integer. The integer determines how many times the message will be printed to the screen. I am using a for loop for the repetition.

My problem now is that when I let the user input the message first and then the integer everything works fine, but when I do it the other way around, it does not let me enter the message after entering the integer. After typing in the integer and pressing enter, it display the prompt for entering the message but then immediately exits the program.

What causes this behaviour?

// This application lets the user enter an integer and a message.
// The message is printed as many times as the integer that was specified.

package en.hkr;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int x;
    String message;

    // Does not work the other way around?
    System.out.print("Enter a message: ");
    message = input.nextLine();
    System.out.print("Enter an integer: ");
    x = input.nextInt();



    // for loop
    for(int i = 0; i < x; i++) {
        System.out.println(message);
    }
}
}
  • 2
    In this case ```nextInt()``` consumes just the integer and ```nextLine()``` will consume the new-line immediately afterwards. Thus your message is empty. I am not quite sure why it is that way and how to solve it (without asking two times for the ```nextLine()```) – Islingre Sep 11 '19 at 19:51

1 Answers1

1

Relevant answer.

Call nextLine AFTER your nextInt call. You need this in order to consume the rest of the line.

System.out.print("Enter an integer: ");
x = input.nextInt();
input.nextLine(); // Add this right here
System.out.print("Enter a message: ");
message = input.nextLine();

Alternatively, you could just use nextLine in place of nextInt and parse it separately. This would have been my approach, due toScanner's sometimes confusing nature.

arcadeblast77
  • 550
  • 2
  • 12