2013-12-09 103 views
1

有人能告诉我如何将错误消息放入以下代码吗?如果用户输入的数字不在0到12之间,我该如何输出“无效输入”。如何显示错误信息

此时程序正常工作,如果输入了无效字符,用户可以再次尝试。

int hours; 
do {     
    System.out.print("Enter hours: "); 
    hours = myscanner.nextInt(); 
} while (hours < 0 || hours > 12); 
+5

'if(....)System.out.println(“Error”);'? – Maroun

+0

如果用户输入的数字不在0到12之间,则循环继续循环。你确定这是你想要的吗? –

+0

不应该反转这个条件:hours <0 ||小时> 12? – periback2

回答

0
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:我也恢复了状态,因为如果布尔值指的是我不喜欢负状态(我更喜欢在有效无效)

+1

为什么downvote? – Cruncher

+0

克朗彻:我写了几个拼写错误,因此有一段时间,当答案中有完整的乱码时 – NeplatnyUdaj

+0

请不要让我失望!我有666个SO点:) – NeplatnyUdaj

-1
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); 
+0

如果你有if语句,没有理由检查两次。改变它一段时间(真),当你得到一个好的输入可能会破坏?我认为这不值得赞扬。选民可以解释吗? – Cruncher

+0

这完美谢谢。 – HungryHenno

+0

@Cruncher当然,这已经是aetheria的主张。我的(显而易见的)解决方案只是为了不扰乱最初的代码。 – mauretto

2

我会用“无限”,而循环,摆脱它时,小时图有效。 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)"); 
} 
+0

+1现在好多了。 – Cruncher

+0

这完美谢谢。 – HungryHenno

+0

这也很好,赶上很可能的异常“InputTypeMismatch”,但它不是问题的一部分... – NeplatnyUdaj