Scanning multiple lines using single scanner object

50,866

Solution 1

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

Solution 2

public class Sol{

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); 

       while(sc.hasNextLine()){

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

    }
}

Solution 3

By default, the scanner uses space as a delimiter. In order to scan by lines using forEachRemaining, change the scanner delimiter to line as below.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    scanner.useDelimiter("\n");
    scanner.forEachRemaining(System.out::println);
}
Share:
50,866
Creative_Cimmons
Author by

Creative_Cimmons

Updated on August 14, 2020

Comments

  • Creative_Cimmons
    Creative_Cimmons over 3 years

    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

  • ifloop
    ifloop about 10 years
    That will not work properly, because in.nextInt() consumes the int value, but not the line break. So your first for-loop iteration will instantly write that line brake into your input[0].
  • Prashanth kumar
    Prashanth kumar over 6 years
    Thanks, a plus one for this line in.nextLine(); //consuming the <enter> from input above