【发布时间】:2017-06-07 08:31:30
【问题描述】:
这里是执行switch的方法(注意switch语句可以正常工作并且符合要求)
public void performChecks() {
priceInput = priceReader.nextDouble();
loop: while(true){
nameInput = nameReader.nextLine();
switch(nameInput){
case "A1": Cola colaItem = new Cola();
if(colaItem.checkPrice(priceInput)){
System.out.println("You ordered " + colaItem.getName()+ ", here is it");
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
}
break loop;
case "B2": Chips chipsItem = new Chips();
if(chipsItem.checkPrice(priceInput)){
System.out.println("You ordered " + chipsItem.getName()+ ", here is it");
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
}
break loop;
case "C3": Crackers crackerItem = new Crackers();
if(crackerItem.checkPrice(priceInput)){
System.out.println("You ordered " + crackerItem.getName()+ ", here is it");
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
}
break loop;
default:
System.out.println("Sorry, we don't have item with such a code");
}
}
}
现在我开始进行一些重构,并将方法放在项目(可乐、薯片和饼干)的超类中,它看起来像这样:
public void performChecks(){
inputPrice = priceReader.nextDouble();
inputCode = codeReader.nextLine();
initializeItems();
for(int i = 0; i < items.length; i++){
if(items[i].checkCode(inputCode)){
if(items[i].checkPrice(inputPrice)){
System.out.println("You ordered " + items[i].getName() + " here it is");
break;
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
break;
}
} else if(!items[i].checkCode(inputCode)){
continue;
} else {
System.out.println("Sorry, we don't have item with such a code");
inputCode = codeReader.nextLine();
}
}
}
问题如下:当我输入正确/错误的价格和不正确的商品代码时,我应该会收到“抱歉,我们没有带有此类代码的商品”消息,并且再次输入项目代码的选项。我已经没有关于如何在
中实现此选项的想法了else if(!items[i].checkCode(inputCode)){
continue;
因为我很确定,它只是卡在那里并且什么也不返回(对于不正确的项目代码)。
【问题讨论】:
-
"我很确定,它只是卡在那里"你试过单步执行代码吗?
-
你有
if(items[i].checkCode(inputCode))然后else if(!items[i].checkCode(inputCode))涵盖这两种情况,不可能到达最后的else子句。 -
SteveSmith - 是的,它卡在那里。我什至不知道,为什么我会这样说:) Berger - 我要面对自己,犯下如此愚蠢的错误......谢谢
标签: java for-loop if-statement switch-statement