Close a Scanner linked to System.in

后端 未结 5 1468
抹茶落季
抹茶落季 2020-11-22 02:57

I have a Scanner linked to System.in. Now, after using the Scanner, I should close it, as it is bad coding practice to leave it open.

5条回答
  •  天命终不由人
    2020-11-22 03:22

    I have vague memories of strange, undiagnosable problems long ago with using the same Scanner of System.in twice, so this is what I use (even though you should probably just use one scanner for the duration of the program):

    static String input() {
        try {
            return new Scanner(System.in).nextLine();
        } catch (NoSuchElementException e) {
            throw e;
        }
    }
    

    For some reason this works without warnings, whereas if I don't do the catch-throw, Eclipse will complain Resource leak: '' is never closed.

提交回复
热议问题