正在解决问题,基本代码如下所示,从用户那里获取4个可能的输入,并根据输入的响应生成响应。但是,我需要添加一个测试来验证4个可能答案中只有1个已被输入。
我知道如何比较4个输入中的2个,但不是所有4个输入,有人可以给我一个想法吗?我宁愿自己弄清楚实际的代码,但正确方向的指针也是有益的。
所以澄清如何 - 如果输入是除了"比尔,通告,明信片或信件"产生错误消息X
System.out.println("What type of Letter has been received?");
System.out.println("Bill, Circular, Postcard or Letter");
String Letter = kybd.nextLine();
{
if (Letter.equalsIgnoreCase("Bill"))
{
System.out.println("Bills must be paid");
}
else if (Letter.equalsIgnoreCase("Circular"))
{
System.out.println("Circulars are thrown away");
}
else if (Letter.equalsIgnoreCase("Postcard"))
{
System.out.println("Postcards are put on the wall");
}
else if (Letter.equalsIgnoreCase("Letter"))
{
System.out.println("Personal letters are read and have replies written for them");
}
}
答案 0 :(得分:1)
if (Letter.equalsIgnoreCase("Bill"))
{
System.out.println("Bills must be paid");
}
else if (Letter.equalsIgnoreCase("Circular"))
{
System.out.println("Circulars are thrown away");
}
else if (Letter.equalsIgnoreCase("Postcard"))
{
System.out.println("Postcards are put on the wall");
}
else if (Letter.equalsIgnoreCase("Letter"))
{
System.out.println("Personal letters are read and have replies written for them");
}else{
System.out.println("ERROR");
}
答案 1 :(得分:1)
你想抛出一个'否则'那里的条件陈述,你可能想看看try和catch块,或者简单地“扔”'您的“其他”中的NoSuchElement例外情况'有条件的。
查看此信息可能对您有用:
http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
在else语句中抛出异常很像我之前的答案,而try ... catch块几乎就是你所说的测试。所以,它看起来像这样:
try
{
Letter != "Bill" //not exactly how it'd look, but this is a general idea on what you'd do here
}
catch (NoSuchElementException e)
{
System.out.println("Not a valid input.");
}