Reputation: 101
This is my own code. And it has a problem. This code works for the "exit" case without any exception, but not for the "countdown" case. I need some help to solve this problem. I use IDEA with java 15.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.Scanner;
import java.time.LocalTime;
import java.util.NoSuchElementException;
class Clock {
public static void run(long time) {
for (long seconds = time; seconds >= 0; seconds--) {
try {
Thread.sleep(1000);
System.out.println(seconds);
} catch (InterruptedException exc) {
System.out.println("Thread interrupted.");
}
}
System.out.println("Done!");
}
public static int getTime() {
int time = 0;
System.out.print("Enter seconds: ");
try (Scanner scan = new Scanner(System.in)) {
time = scan.nextInt();
} catch (NoSuchElementException exc) {
System.out.println("NumberFormatException: " + exc);
}
return time;
}
public static void main(String args[]) throws Exception {
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
for (; ;) {
System.out.println("What type of alarm will you choose? 1 - countdown, 2 - particular time, 3 - exit: ");
String action = scan.readLine();
switch (action) {
case "countdown":
long time = 0;
if (args.length == 1) {
time = Integer.parseInt(args[0]);
} else {
time = getTime();
}
run(time);
break;
case "exit":
System.out.println("Bye bye!");
System.exit(0);
break;
}
}
}
}
I got this exception after the compilation of my code (above): Exception in thread "main" java.io.IOException: Stream closed
Upvotes: 0
Views: 826
Reputation: 545588
Don’t close a scanner (especially over System.in
), since it also closes the underlying stream.
The code try (Scanner scan = new Scanner(System.in))
auto-closes the scanner at the end of the scope.
Upvotes: 2
Reputation: 2981
The problem is that in getTime()
you are implicitely closing the System.in
in the try-with-resources. Do not do that.
Upvotes: 1