1

I want to make a program that will read user inputs and will printout them gradually. But when I am running the code, in the Console area, the first line is automatically skipping. But when I am taking input as Integer, all is running well. Where is my fault?

import java.util.*;

public class MainClass {
    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {

        int limit, i, j;
        System.out.print("How many names you want to take: ");
        limit = input.nextInt();
        String[] name = new String[limit];

        for (i = 0; i < name.length; i++) {
            System.out.print("Enter your name: ");
            name[i] = input.nextLine();
        }

        for (String output : name) {
            System.out.println("Names are: " + output);
        }

    }
}

Console area:

How many names you want to take: 3
Enter your name: Enter your name: Saon
Enter your name: Srabon
Names are: 
Names are: Saon
Names are: Srabon
Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141

1 Answers1

1

Invoke input.nextLine() after the input.nextInt() in order to clear the new line character produced by pressing Enter key (when you enter int number);

Alternatively, you can read your int as Integer.valueOf(input.nextLine()).

Giorgi Tsiklauri
  • 6,699
  • 7
  • 29
  • 54