-1
=========Menu Bagian Server=========
1. Start Server
2. server room
2. Exit
=============================================
Masukkan Pilihan: masukkan angka! 

Exception in thread "main" java.util.NoSuchElementException: No line found
  at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
  at com.company.Server.menuServer(Server.java:35)

at com.company.Server.main(Server.java:17)

Process finished with exit code 1

here is the code, how to make the menu loop again so i can start the server after it terminated

public static void serverRoom() throws IOException{
   din = new DataInputStream(s.getInputStream());
   dout = new DataOutputStream(s.getOutputStream());
    try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
        String str = "", str2;
        while (!str.equalsIgnoreCase("Exit")) {
            str = din.readUTF();
            System.out.println("client says: " + str);
            str2 = br.readLine();
            dout.writeUTF(str2);
            dout.flush();
        }
        din.close();
        s.close();
        ss.close();
    }
JS24
  • 1
  • 2
  • 14
  • Does this answer your question? [java.util.NoSuchElementException - Scanner reading user input](https://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input) – Savior Jun 10 '21 at 14:21

1 Answers1

0

InputStreamReader and BufferedReader are so-called filter streams: They don't themselves represent a resource that must be closed; they wrap around some other resource.

The rule is, if you close a filterstream, it closes the thing they wrapped. (So, calling close() on br will cause that bufferedreader to invoke close() on that new InputStreamReader object, which in turn causes it to call close on System.in.

Here's the thing, while usually you want to always close resources, you do not want to close System.in!

You are, here, by using the try construct.

Solution: Just.. do not do that. Do not make a try() {} block here.

Your IDE might complain. Tell it to shut up, it is wrong.

You get this error because the code closes System.in (by reaching the end of the try-with-resources block, which invokes close() on the resource, which invokes close() on the ISR, which invokes close() on System.in), and once it is closed, no further lines can be read from it.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72