Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

后端 未结 22 1093
北荒
北荒 2020-12-03 01:14

I\'m writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say

22条回答
  •  醉梦人生
    2020-12-03 01:58

    java.util.Scanner; util - package, Scanner - Class

    1. next() reads the string before the space. it cannot read anything after it gets the first space.
    2. nextLine() reads the whole line. Read until the end of the line or "/n". Note: Not The Next line

    (Example)

    My mission in life is not merely to survive, but to thrive;

    and to do so with some passion, some compassion, some humor.

    (Output)

    1. My

    2. My mission in life is not merely to survive, but to thrive;

    Tricks:

    If you want to read the next line Check Java has method.

    while (scanner.hasNext()) {
        scan.next();
    }
    
    while (scanner.hasNext()) {
        scan.nextLine();
    }
    

提交回复
热议问题