【发布时间】:2020-02-10 20:55:53
【问题描述】:
抱歉标题不好,我不知道更好的解释..
所以我目前正在编写一个杂货清单程序,但我被我的 addItemsToList 方法困住了。基本上我希望它必须“退出”点。其中之一将带您回到应用程序的主菜单,其中之一将带您回到 addItemsToList 方法的上下文菜单。 不幸的是,我完全被卡住了。
这是我的方法代码:
private static void addItemsToList(){
System.out.println("To which category do you want to add? ");
categoryInstructions();
int choice2 = scan.nextInt();
if(choice2 == 5){ // i am "getting out" here just fine
interact(); // this is the method that instructs everything to happen in the main method
}else {
System.out.println("What do you want to add? Type 'exit' for menu");
i = scan.next(); // this is where the second "exit" point is supposed to be if someone types "exit"
if (i.compareTo(exit) != 0) {
System.out.println("Please enter the quantity ");
int quant = scan.nextInt();
if (choice2 == 1) {
GrocerieList.foodstuffsList.add(i);
GrocerieList.foodstuffsAmount.add(quant);
} else if (choice2 == 2) {
GrocerieList.hygeneList.add(i);
GrocerieList.hygeneAmount.add(quant);
} else if (choice2 == 3) {
GrocerieList.drinkList.add(i);
GrocerieList.drinkAmount.add(quant);
} else if (choice2 == 4) {
GrocerieList.otherList.add(i);
GrocerieList.otherAmount.add(quant);
}
} else {
addItemsToList();
}
}
}
为了更好地理解这里是 categoryInstructions():
public static void categoryInstructions(){
System.out.println("Press");
System.out.println(" ");
System.out.println("\t\t" + "(1)" + "\t--\t" + "for foodstuffs");
System.out.println("\t\t" + "(2)" + "\t--\t" + "for hygene");
System.out.println("\t\t" + "(3)" + "\t--\t" + "for drinks");
System.out.println("\t\t" + "(4)" + "\t--\t" + "for others");
System.out.println(" ");
System.out.println("\t\t" + "(5)" + "\t--\t" + "to get back main menu");
}
现在发生的事情是,如果choice2 == 5,我可以完全退出 addItemsToList,但如果我等于“退出”,我似乎无法找到退出的逻辑解决方案。我让它在应用程序中快速而肮脏地工作,首先询问数量然后退出,但这并不是我想要的。
由于我(显然)是初学者,因此我的风格中的任何其他 cmet 也将不胜感激!
【问题讨论】:
-
TL;DR
return; -
return将退出当前方法。尽管在您的情况下,我会将if(choice2 == 5)更改为if(choice2 != 5)并使用它来进入下一个逻辑流程,否则只需让代码运行到方法的末尾,它将自动返回给调用者 -
如果在第二个出口处添加
if(i.equalsIgnoreCase("exit")){ interact(); }会怎样。