Scanner in Java not working

后端 未结 2 473
一个人的身影
一个人的身影 2021-01-02 20:59

I\'m trying to write a very simple number guessing game (code is below). After 1 round is finished, the user is supposed to be able to decide whether he/she wants to play an

相关标签:
2条回答
  • 2021-01-02 21:16

    Use scan.next()+ scan.nextLine(); instead eg.

    Scanner scan = new Scanner(System.in);
    
    String s = scan.nextLine() +scan.nextLine();
    

    Problem occurs because the last newline character for the last line of input is still queued in the input buffer and the next nextLine() will be reading the remainder of the line (which is empty). So, when you use next it goes to the next token, then you can get the remaining input using nextLine()

    0 讨论(0)
  • 2021-01-02 21:21

    Use want = scan.next(); instead of nextLine().

    The reason for your problem is that following the preceding nextInt(), you're still on the same line, and nextLine() returns the rest of the current line.

    Here's a smallest snippet to reproduce the behavior:

    Scanner sc = new Scanner(System.in);
    System.out.println("nextInt() = " + sc.nextInt());
    System.out.println("nextLine() = " + sc.nextLine());
    

    When you type in, say, 5 and then hit Enter, the output is:

    nextInt() = 5
    nextLine() = 
    

    That is, nextLine() did not block for your input, because the current line still has an empty string remaining.

    For comparison, when you type in, say 5 yeah! and then hit Enter, then the output is:

    nextInt() = 5
    nextLine() =  yeah!
    

    Note that " yeah!" actually comes from the same line as the 5. This is exactly as specified in the documentation:

    String nextLine(): Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.


    On half-open ranges

    Assuming that the number to guess is between 1 and 10 inclusive, the following code is "wrong":

    numRandom = rand.nextInt(9)+1; // this can only be in 1..9 range inclusive!
    

    Here's an excerpt from the documentation of java.util.Random:

    int nextInt(int n): Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

    That is, like a lot of methods in Java's API, Random.nextInt(int) uses the half-open range, with inclusive lower bound and exclusive upper bound.

    Related questions

    • Are upper bounds of indexed ranges always assumed to be exclusive?
    0 讨论(0)
提交回复
热议问题