有人能告诉我如何将错误消息放入以下代码吗?如果用户输入的数字不在0到12之间,我该如何输出“无效输入”。如何显示错误信息
此时程序正常工作,如果输入了无效字符,用户可以再次尝试。
int hours;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
} while (hours < 0 || hours > 12);
有人能告诉我如何将错误消息放入以下代码吗?如果用户输入的数字不在0到12之间,我该如何输出“无效输入”。如何显示错误信息
此时程序正常工作,如果输入了无效字符,用户可以再次尝试。
int hours;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
} while (hours < 0 || hours > 12);
int hours;
boolean valid;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
valid = (hours >= 0 && hours <= 12);
if (!valid)
System.out.println("Invalid entry");
} while (!valid);
注:我添加了一个变量,因为否则的话,你就必须重复的条件有 NOTE2:我也恢复了状态,因为如果布尔值指的是我不喜欢负状态(我更喜欢在有效无效)
为什么downvote? – Cruncher
克朗彻:我写了几个拼写错误,因此有一段时间,当答案中有完整的乱码时 – NeplatnyUdaj
请不要让我失望!我有666个SO点:) – NeplatnyUdaj
int hours;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
if (hours < 0 || hours > 12) System.out.println("Please insert a valid entry");
} while (hours < 0 || hours > 12);
如果你有if语句,没有理由检查两次。改变它一段时间(真),当你得到一个好的输入可能会破坏?我认为这不值得赞扬。选民可以解释吗? – Cruncher
这完美谢谢。 – HungryHenno
@Cruncher当然,这已经是aetheria的主张。我的(显而易见的)解决方案只是为了不扰乱最初的代码。 – mauretto
我会用“无限”,而循环,摆脱它时,小时图有效。 while(true) { ... }
是惯用的Java。
Scanner scanner = new Scanner(System.in);
int hours;
while (true) {
System.out.print("Enter hours: ");
hours = scanner.nextInt();
if (hours >= 0 && hours <= 12) {
break;
}
System.err.println("Invalid entry (should be 0-12)");
}
+1现在好多了。 – Cruncher
这完美谢谢。 – HungryHenno
这也很好,赶上很可能的异常“InputTypeMismatch”,但它不是问题的一部分... – NeplatnyUdaj
'if(....)System.out.println(“Error”);'? – Maroun
如果用户输入的数字不在0到12之间,则循环继续循环。你确定这是你想要的吗? –
不应该反转这个条件:hours <0 ||小时> 12? – periback2