Scanning multiple lines using single scanner objec

2019-03-15 13:21发布

I a newbie to java so please don't rate down if this sounds absolute dumb to you

ok how do I enter this using a single scanner object

5

hello how do you do

welcome to my world

6 7

for those of you who suggest

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

check it out, it does not work!!!

thanks

4条回答
疯言疯语
2楼-- · 2019-03-15 14:10
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);
    }
}

Sample execution:

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

Your input:
Line1
Line2
Line3
查看更多
Root(大扎)
3楼-- · 2019-03-15 14:10

try this code

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);
}
查看更多
老娘就宠你
4楼-- · 2019-03-15 14:11

You can try only with lambda too:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    scanner.forEachRemaining(input -> System.out.println(input));
}
查看更多
放我归山
5楼-- · 2019-03-15 14:12
public class Sol{

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); 

       while(sc.hasNextLine()){

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

    }
}
查看更多
登录 后发表回答