Pergunta

I'm trying out a very simple Java program that uses Scanner and its method next(), and somehow I encounter a weird situation. Here is the code:

import java.util.Scanner;
public class Test
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        String input = "";

        System.out.println("Enter a sentence here: ");

        while(!input.endsWith("."))
        {
            input = scan.next();
            System.out.println("Echo: " + input);
        }
    }
}

If I run it in Scite, everytime I type a space after a word, the line "Echo: " + the inputted word will be printed right after the the space.

Suppose I type the input in keyboard like this:

apple orange mango.

In scite it will look like this:

Enter a sentence here:
apple Echo: apple
orange Echo: orange
mango. Echo: mango.

But if I run it in command prompt and type the same input, it will look like this :

Enter a sentence here: 
apple orange mango.
Echo: apple
Echo: orange
Echo: mango.

Note: when running in command prompt, I must hit enter after I type "apple orange mango." or it will not print the "Echo" sentences. Also tried the code in NetBeans and it gave the same results as the command prompt one.

Why does the program act differently?

Foi útil?

Solução

Buffering. At the command prompt, and apparently in NetBeans, the stdin stream is line-buffered, so your app doesn't know you've typed anything before you've entered a newline (or the buffer is full). Scite apparently doesn't line-buffer the input stream but flushes it either after each character or at each space.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top