Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanning multiple lines using single scanner object

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

like image 676
Creative_Cimmons Avatar asked Apr 08 '14 07:04

Creative_Cimmons


People also ask

What does Scanner split do?

Using Scanner. It splits the string into tokens by whitespace delimiter. The complete token is identified by the input that matches the delimiter pattern.

What is the use of nextLine () method in Scanner class?

The nextLine() method of java. util. Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end.

Can you use the same Scanner twice in Java?

You can get multiple user inputs from the same instance of Scanner. Here is an example: Scanner input = new Scanner(System.in); int x = input. nextInt(); int y = input.


1 Answers

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
like image 50
ifloop Avatar answered Sep 23 '22 00:09

ifloop