Scanner.next() and Scanner.nextLine()

前端 未结 3 1079
不思量自难忘°
不思量自难忘° 2021-01-28 15:10

I have the following code:

Scanner in = new Scanner (System.in);
String[] data = new String[5];

System.out.println(\"Please, enter the name of the customer orde         


        
相关标签:
3条回答
  • 2021-01-28 15:43

    Don't use next() and nextLine() together if you don't know what you're doing, it easily results in errors. next() reads the next input token, nextLine() all tokens until next line. So if you have inputs like this:

    John\nSquirrels

    (\n is newline character)

    The first next() returns "John" and leaves us

    \nSquirrels

    After which a nextLine() is facing no tokens before the end of the line, so you get an empty String instead of "Squirrels".

    0 讨论(0)
  • 2021-01-28 15:47

    This should work:

        Scanner in = new Scanner (System.in);
        String[] data = new String[5];
    
        System.out.println("Please, enter the name of the customer ordering:");
        data[0] = in.nextLine();
        System.out.println("Please, enter the assembly details: ");
        data[1] = in.nextLine();
        System.out.println("Please, enter the assembly id:");
        data[2] = in.nextLine();
        System.out.println("Please, enter the date the assembly was ordered (MM-DD-YYYY):");
        data[3] = in.nextLine();
        in.close();
    

    You should be using nextLine() and not next() to read each line from console

    0 讨论(0)
  • 2021-01-28 16:04

    next() -- Finds and returns the next complete token from this scanner nextLine() --Advances this scanner past the current line and returns the input that was skipped.

    From the java API documentation.

    0 讨论(0)
提交回复
热议问题