Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k 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 (19.7k 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
0 votes
1 answer
asked Jul 11, 2020 in Python by ashely (50.2k points)

Browse Categories

...