我知道return语句并尝试过。 System.exit(0)也是这样。但在这里使用它会终止程序。有什么办法可以使用,以便如果用户键入除1-7以外的其他输入,程序不会终止,这样我就不必重新编译和重新运行该程序?或者在Java中不可能?是否可以在不终止程序的情况下退出主方法?
import java.util.Scanner;
public class NewShoppingCart{
public static void main(String args[]) {
boolean flag = true;
long code;
String choice;
NewShop aShop = new NewShop();
Scanner sc = new Scanner(System.in);
Integer parse = 0;
System.out.println("-----ITEM------");
do {
System.out.println("1. Display all items");
System.out.println("2. Search items");
System.out.println("3. Add items to list");
System.out.println("4. Add items to cart");
System.out.println("5. Display cart");
System.out.println("6. Issue item");
System.out.println("7. Exit");
System.out.println("Choice:");
choice = sc.nextLine();
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
if (parse >=1 && parse <= 7)
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
}
while (flag != false);
sc.close();
}
}
nop,这是应用程序的主要入口...一旦你返回该方法,该应用程序就不见了! –
只记录异常不要从那里返回,那么你的while循环将继续并要求再次输入 – Sikorski
当程序终止时,不需要重新编译程序。除非程序自行删除。 – Kayaman