我有一个必须使用 switch 的任务。当输入整数 -1 时,程序应该终止。1 到 7 之间的任何数字都将显示一周中的某一天。1 到 7 和 -1 之间的任何其他数字将显示:“仅接受 1 到 7 的数字”。输入-1时如何使程序终止。这是到目前为止的代码:
Scanner s = new Scanner(System.in);
String res = "";
System.out.println("Input a number ");
int day = s.nextInt();
if(day==-1){
System.exit(0);
}
switch (day) {
case 1:
res="Today is Sunday";
break;
case 2:
res="Today is Monday";
break;
case 3:
res = "Today is Tuesday";
break;
case 4:
res = "Today is Wednesday";
break;
case 5:
res = "Today is Thursday";
break;
case 6:
res = "Today is Friday";
break;
case 7:
res = "Today is Saturday";
break;
default:
res = "Only numbers from 1 to 7 are accepted ";
break;
}
System.out.println(res);
}
}
用我的解决方案更新了代码。