0 votes
1 view
in Java by (9.2k points)

How do I enter the below lines with a single scanner object? 

5

hello how do you do

Welcome to my world

6 7

1 Answer

0 votes
by (19k points)

Check out the below code: 

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

    }

}


 

The above code executes as: 

Please specify how many lines you want to enter: 3

Line1

Line2

Line3

Your input:

Line1

Line2

Line3

Interested in Java? Check out this Java Certification by Intellipaat.

Related questions

0 votes
1 answer
asked Mar 23 in Java by sheela_singh (9.2k points)
0 votes
1 answer
asked Mar 20 in Java by Jake (6.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...