0

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

Community
  • 1
  • 1
Cataclysm
  • 7,592
  • 21
  • 74
  • 123

1 Answers1

2

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();
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89