Intellipaat 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

2 Answers

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.

0 votes
by (1.7k points)

To scan multiple lines in one step with a single `Scanner` object in Java, use the following code:


 

import java.util.Scanner;

public class MultiLineScanner {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Read the first integer

int number = scanner.nextInt();

scanner.nextLine(); // Consume the newline



 

// Read subsequent lines

String line1 = scanner.nextLine();

String line2 = scanner.nextLine();

String line3 = scanner.nextLine();



 

// Close the scanner

scanner.close();

}

}

This code allows you to enter:

5

hello how do you do

Welcome to my world

6 7

and reads them into variables using a single Scanner instance.

Related questions

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...