search

Home  >  Q&A  >  body text

标准输入 - java中Scanner的hasNext()的疑问

大家讲道理大家讲道理2812 days ago736

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:48:30

    The first question is that the difference between the two pieces of code lies in the different blocking positions. You can clearly see the difference by adding a line of output code.

    Test.java

    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            while(s.hasNext())
            {
                System.out.print("You inputted: ");
                System.out.println(s.next());
            }
        }
    }

    In addition, the hasNext() method will block, but it does not mean that the next() method will not block.

    /**
     * Returns true if this scanner has another token in its input.
     * This method may block while waiting for input to scan.
     * The scanner does not advance past any input.
     *
     * @return true if and only if this scanner has another token
     * @throws IllegalStateException if this scanner is closed
     * @see java.util.Iterator
     */
    public boolean hasNext() {
        ensureOpen();
        saveState();
        while (!sourceClosed) {
            if (hasTokenInBuffer())
                return revertState(true);
            readInput();
        }
        boolean result = hasTokenInBuffer();
        return revertState(result);
    }
    /**
     * Finds and returns the next complete token from this scanner.
     * A complete token is preceded and followed by input that matches
     * the delimiter pattern. This method may block while waiting for input
     * to scan, even if a previous invocation of {@link #hasNext} returned
     * <code>true</code>.
     *
     * @return the next token
     * @throws NoSuchElementException if no more tokens are available
     * @throws IllegalStateException if this scanner is closed
     * @see java.util.Iterator
     */
    public String next() {
        ensureOpen();
        clearCache
        while (true) {
            String token = getCompleteTokenInBuffer(null);
            if (token != null) {
                matchValid = true;
                skipped = false;
                return token;
            }
            if (needInput)
                readInput();
            else
                throwFor();
        }
    }

    Second question, if you want to end the loop, you need to enter Ctrl+Z in the Windows environment; and in the Unix environment, you need to enter Ctrl+D. Note that this is input, not manipulation of the console. This is equivalent to entering a character into the console, which represents EOF. At this time, the hasNext() method returns false and the loop ends.

    reply
    0
  • 黄舟

    黄舟2017-04-17 14:48:30

    The blocking positions are different

    reply
    0
  • Cancelreply