public static void main(String[] args)
{
CollegeTester ct = new CollegeTester();
ct.getCommand();//goes to command
}
//Ask user for a command
public void getCommand()
{
String command = "";
System.out.println("Enter a command: ");
command = input.nextLine();
if(command.equals("add"))
addCommand();//If command is add go to addCommand
if(command.equals("course"))
courseCommand();//If command is course go to courseCommand
if(command.equals("find"))
findCommand();
if(command.equals("remove"))
removeCommand();
if(command.equals("highest"))
highestCommand();
if(command.equals("login"))
loginCommand();
if(command.equals("quit"))
System.exit(1);
}
我想重复getCommand()方法,直到用户输入quit但它总是失败
我试图将getCommand()放在每个其他方法的末尾& if语句不会重复
我试图为所有事情做一个while循环,但如果有人意外地输入错误类型退出程序永远不会结束
在用户希望退出之前,我将如何有效地返回此方法?
答案 0 :(得分:2)
我会用两种方法之一。
public static void main(String[] args)
{
CollegeTester ct = new CollegeTester();
ct.getCommand();//goes to command
}
//Ask user for a command
public void getCommand()
{
boolean exit = false;
while(!exit){
String command = "";
System.out.println("Enter a command: ");
command = input.nextLine();
if(command.equals("add")){
addCommand();//If command is add go to addCommand
}else if(command.equals("course")){
courseCommand();//If command is course go to courseCommand
}else if(command.equals("find")){
findCommand();
}else if(command.equals("remove")){
removeCommand();
}else if(command.equals("highest")){
highestCommand();
}else if(command.equals("login")){
loginCommand();
}else if(command.equals("quit")){
exit = true;
}else {
System.out.println("Not valid command, try again.");
}
}
}
//Ask user for a command
public void getCommand()
{
while(true){
String command = "";
System.out.println("Enter a command: ");
command = input.nextLine();
if(command.equals("add"))
addCommand();//If command is add go to addCommand
if(command.equals("course"))
courseCommand();//If command is course go to courseCommand
if(command.equals("find"))
findCommand();
if(command.equals("remove"))
removeCommand();
if(command.equals("highest"))
highestCommand();
if(command.equals("login"))
loginCommand();
if(command.equals("quit"))
System.exit(0); // or could use 'break' here (thanks Mikkel)
}
}
编辑:更正了System.exit(1)。谢谢Mikkel。
答案 1 :(得分:1)
或者你可以把它放在while循环中:
while(true) {
getCommand();
}
另外,请查看this question on System.exit(int),您实际上是说应用程序应该因为错误而关闭。如果要关闭,您应该通过0
,而不是1
。
事实上,如果你使用像上面这样的while循环,我可能只是通过return false;
或其他东西逃避循环,让程序自然结束。