使用单个扫描仪对象扫描多条线

2022-09-04 07:21:25

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

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

5

你好你好

欢迎来到我的世界

6 7

对于那些建议的人

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

检查出来,它不起作用!!!

谢谢


答案 1
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

答案 2
public class Sol{

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); 

       while(sc.hasNextLine()){

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

    }
}

推荐