[Solved] Why cannot I return values from two functions in Java?


Closing the Scanner also closes the input stream it’s scanning — in this case System.in. Hence, when you subsequently call getYear(), it finds the input stream System.in already closed.

One way to avoid this is to use the same Scanner in both methods, by passing it as an argument to the methods.

From the Java API docs for Scanner.close():

public void close()

Closes this scanner.

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable’s close method will be invoked. If this scanner is already closed then invoking this method will have no effect.

By the way, the purpose of the loops in getMonth() and getYear() are unclear. If you want to continue scanning until a valid value is entered, then you want to include a call to Scanner.nextInt() inside the loops. And consider using a do-while statement, since you know you want to read at least one value.

2

solved Why cannot I return values from two functions in Java?