Cataclysm
Cataclysm

Reputation: 8558

How to read the user inputs(including spaces) line by line with Scanner?

I need to read user inputs line by line (may be included spaces). I had already read Scanner doesn't see after space question. So I used with scanner.nextLine() but this method does not help my program. Below is my sample program ....

public class TestingScanner {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("How many friends do you have ?");
    int size = sc.nextInt();
    String[] names = new String[size];
    for (int i = 0; i < size; i++) {
        System.out.println("Enter your name of friend" + (i + 1));
        names[i] = sc.nextLine();
    }
    System.out.println("*****************************");
    System.out.println("Your friends are : ");
    for (int i = 0; i < names.length; i++) {
        System.out.println(names[i]);
    }
    System.out.println("*****************************");
    }
}

While runnig my program , after inserted no: of friend , my program produces two lines as below. How can I solve it ? Thanks.

enter image description here

Upvotes: 0

Views: 143

Answers (1)

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

After int size = sc.nextInt(); use sc.nextLine() to consume the newline characters, otherwise, they will be consumed by nextLine() in your loop and that is not what you want.


Solution

int size = sc.nextInt();
sc.nextLine();

Upvotes: 2

Related Questions