使用单个扫描仪对象扫描多行

问题描述 投票:12回答:4

我是java的新手,所以如果这听起来绝对愚蠢,请不要降价

好吧如何使用单个扫描仪对象输入此内容

5

你好,你怎么样

欢迎来到我的世界

6 7

对于那些建议的人

scannerobj.nextInt->nextLine->nextLine->nextInt->nextInt,,,

检查出来,它不起作用!

谢谢

java input output java.util.scanner
4个回答
20
投票
public static void main(String[] args) {
    Scanner  in    = new Scanner(System.in);

    System.out.printf("Please specify how many lines you want to enter: ");        
    String[] input = new String[in.nextInt()];
    in.nextLine(); //consuming the <enter> from input above

    for (int i = 0; i < input.length; i++) {
        input[i] = in.nextLine();
    }

    System.out.printf("\nYour input:\n");
    for (String s : input) {
        System.out.println(s);
    }
}

样品执行:

Please specify how many lines you want to enter: 3
Line1
Line2
Line3

Your input:
Line1
Line2
Line3

1
投票
public class Sol{

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); 

       while(sc.hasNextLine()){

           System.out.println(sc.nextLine());
       }

    }
}

0
投票

试试这段代码

Scanner  in    = new Scanner(System.in);

System.out.printf("xxxxxxxxxxxxxxx ");        
String[] input = new String[in.nextInt()];

for (int i = 0; i < input.length; i++) {
    input[i] = in.nextLine();
}

for (String s : input) {
    System.out.println(s);
}

0
投票

你也可以只尝试使用lambda:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    scanner.forEachRemaining(input -> System.out.println(input));
}
© www.soinside.com 2019 - 2024. All rights reserved.