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

后端 未结 22 1092
北荒
北荒 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:54

    the below piece of code should do what yoiu are looking for:

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        System.out.println(s);
        scan.close();
    }
    
    0 讨论(0)
  • 2020-12-03 01:55

    "it only prints a word lets say only 'Archbishop' from 'Archbishop Street"

    It is only printing the word because Scanner functions such as next(), nextInt(), etc. read only a token at time. Thus this function reads and returns the next token.

    For example if you have: x y z
     s.next() will return x
     s.nextLine() y z
    

    Going back to your code if you want to read the whole line "Archbishop Street"

    String address = s.next(); // s = "Archbishop"
    Then address += s.nextLine(); // s = s + " Street"
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-12-03 01:58

    Use nextLine() instead of next() for taking sentence as string input.

    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    
    0 讨论(0)
  • 2020-12-03 02:03

    I set the token delimiter to be a newline pattern, read the next token, and then put the delimiter back to whatever it was.

    public static String readLine(Scanner scanner) {
            Pattern oldDelimiter = scanner.delimiter();
            scanner.useDelimiter("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
            String r = scanner.next();
            scanner.useDelimiter(oldDelimiter);
            return r;
    }
    
    0 讨论(0)
  • 2020-12-03 02:05

    I would use Scanner#nextLine opposed to next for your address attribute.

    This method returns the rest of the current line, excluding any line separator at the end.

    Since this returns the entire line, delimited by a line separator, it will allow the user to enter any address without any constraint.

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