简体   繁体   中英

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.

在此处输入图片说明

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM