目前,当我输入1时,它输出“待机模式已启用”以及“待机模式已禁用”,并且每5分钟循环输出“待机模式已禁用”。在输入1后,如何仅在5分钟内输出“待机模式已启用”以及输出“待机模式已禁用”。
以下是代码:
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class StandbyMode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Standby Mode");
System.out.println("Press 1 for Standby mode");
int selectedOption = scanner.nextInt();
if(selectedOption == 1){
System.out.println("Standby mode is enabled");
}else {
System.out.println("Invalid input");
}
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Standby Mode disabled");
}
}, 0, 300000);
scanner.close();
}
}
答案 0 :(得分:0)
您可以在if
语句中使用Timer作为启用模式:
if(selectedOption == 1){
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Standby mode is enabled.");
}
}, 0, 300000);
} else {
System.out.println("Standby mode is disabled.");
}
注意 :在定义中禁用模式和无效输出之间必须有一条线,有点像:
else if(selectedOption==2) {
System.out.println("Standby mode is disabled.");
} else {
System.out.println("Invalid input");
}
编辑 (评论后)::对于交替模式,您可以使用标志在计时器显示的消息之间切换:
if (selectedOption == 1) {
Timer t = new Timer();
t.schedule(new TimerTask() {
boolean flag = true;
@Override
public void run() {
if (!flag) {
System.out.println("Standby Mode Disabled");
} else {
System.out.println("Standby Mode Enabled");
}
flag = !flag;
}
}, 0, 3);
} else {
System.out.println("Invalid input");
}