0

I am reading the Deitel book and it says there is a key sequence CTRL z that terminates the Scanner Input.so I wrote a similar code in NetBeans IDE(a code similar to the Deitel's book)

        Scanner y = new Scanner(System.in);
        String g;
        while(y.hasNext())
        {
            g = y.nextLine();
            System.out.println(g);
        }

but as I press CTRL-z after entering some input,nothing happens. Does such a thing exist in java(EOF key sequence)?I have also visited the page How to terminate Scanner when input is complete? but the suggested codes didn't work for me.

Community
  • 1
  • 1
Geralt
  • 113
  • 9
  • 2
    [https://netbeans.org/bugzilla/show_bug.cgi?id=224311](https://netbeans.org/bugzilla/show_bug.cgi?id=224311) – resueman May 09 '16 at 13:00
  • Well, you shouldn't use that to close the stream anyway, since this will prevent you from requesting more input later in the program. You can try something like code work, to finish the input for this moment. Like `String s = y.next(); if (y.equals("stop") break;`. – Tom May 09 '16 at 13:03
  • I have used it so far.String terminator is okay I was going to see whether there is a combination of keys that does the same thing or not.BTW thank you – Geralt May 09 '16 at 13:07

2 Answers2

0

The end-of-file terminator is platform specific ... and typically implemented outside of the control of Java.

On Windows ^Z is used, but on Linux / Unix based systems ^D is the normal EOF character ... when accepting characters from a "tty" or equivalent.

Try ^D.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Do this:

while (input.hasNext()) // faz um loop até o indicador de fim de arquivo
{
    try
    {
        // gera saída do novo registro para o arquivo; supõe entrada válida
        output.format("%d %s %s %.2f%n", input.nextInt(),
        input.next(), input.next(), input.nextDouble());
    }
    catch (FormatterClosedException formatterClosedException)
    {
        System.err.println("Error writing to file. Terminating.");
        break;
    }
    catch (NoSuchElementException elementException)
    {
        System.err.println("Invalid input. Terminating.");
        break; // descarta entrada para o usuário tentar de novo
    }

    System.out.print("? ");

} // fim do while
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197