我如何使用带有switch case的try-catch语句但循环swich case?

时间:2022-10-30 16:13:18

I am very new to Java and im trying to use try-catch statements. I would like to add a try catch case, but when i add it, the message just prints once and ends. I woudl like to reprint:

我是Java的新手,我试图使用try-catch语句。我想添加一个try catch情况,但是当我添加它时,消息只打印一次并结束。我想转载:

System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
        System.out.println("Typing other numbers will end the Chatbot");

but the program just ends. Is there a way to loop the try-catch statement?

但该计划刚刚结束。有没有办法循环try-catch语句?

    Scanner userinput = new Scanner(System.in);
    int startup;
    //popup for 1 to chat, 2 to play and 3 to edit
    while (true) {
        try {
            System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
            System.out.println("Typing other numbers will end the Chatbot");
            startup = userinput.nextInt();
            switch (startup) {

                case 1:
                    ConversationBot chat = new ConversationBot();
                    chat.ChattingBot();
                    break;
                case 2:
                    GameBot game = new GameBot();
                    game.GamingBot();
                    break;
                case 3:
                    EditBot edit = new EditBot();
                    edit.EditingBot();
                    break;
                default:
                    System.exit(0);
            }
        } catch (InputMismatchException e) {
            System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
            break;
        }
        String returningCode = returnChoiceOfChatbot(startup);
        System.out.println(returningCode);
    }

Thank you for the help. BTW this is the returnChoiceOf Chatbot method

感谢您的帮助。 BTW这是returnChoiceOf Chatbot方法

public static String returnChoiceOfChatbot(int input) {
    String returnChoice = null;
    switch (input) {
        case 1:
            returnChoice = ("You have chosen to chat with me!");
            break;
        case 2:
            returnChoice = ("you have chsen to play word games with me!");
            break;
        case 3:
            returnChoice = ("Please enter an input that you would give to the Chatbot.");
            break;
        default:
            System.exit(0);
    }
    return returnChoice;

}//end of returnChoice method    

3 个解决方案

#1


2  

You need to replace the line break; with continue; in your catch block. You want to ask the user for a new input if it wasn't a number. Otherwise that break breaks the whole while loop and prevents it from running again. This said, it should read:

你需要更换换行符;继续;在你的拦截块中。如果用户不是数字,您想要询问用户输入新内容。否则该中断会破坏整个循环并阻止它再次运行。这说,它应该是:

    } catch (InputMismatchException e) {
        System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
        continue; // Jump back to the beginning of the while-loop
    }

Also check if you need to move these two lines:

还要检查是否需要移动这两行:

String returningCode = returnChoiceOfChatbot(startup);
System.out.println(returningCode);

outside of your while loop. While it's not clear to me what they are for, it looks like you might want to run them only once after the while loop was left.

在你的while循环之外。虽然我不清楚它们的用途,看起来你可能只想在while循环离开后运行它们一次。

#2


0  

} catch (InputMismatchException e) {
    System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
    break;
}

Just remove the break. It doesn't have anything to do with the catch specifically, just with the break that you wrote in it.

只需删除休息时间。它与捕获没有任何关系,只是与你在其中写的断点。

#3


0  

The break statement (when used without a label to specify what to break out of) will exit the nearest switch, while, for or do .. while loop.

break语句(在没有标签的情况下用于指定要突破的内容)将退出最近的开关,而for,for或while .. while循环。

You generally have to use it with switch as you do to stop the execution falling through to the next case - e.g. if you didn't have the breaks and the user selected 1, it would execute the code for all three cases, and then exit the program.

您通常必须将其与开关一起使用,以阻止执行进入下一种情况 - 例如如果你没有中断并且用户选择了1,它将执行所有三种情况的代码,然后退出程序。

Inside your catch block however, the break exits the while loop. Since the intention is to tell the user their input is invalid and then ask for new input, this isn't what you want to do here. You could change the break to a continue which would abort the current iteration of the while loop and start the loop again, however generally speaking this sort of flow control will make your program harder to follow and therefore maintain.

然而,在catch块内部,break会退出while循环。由于目的是告诉用户他们的输入无效然后请求新输入,这不是你想要做的。您可以将break更改为continue,这将中止while循环的当前迭代并再次启动循环,但一般来说,这种流控制将使您的程序更难以遵循并因此维护。

I'm guessing you put the last break in to skip over the returnChoiceOfChatbot(...) code when the input is invalid. But this is exactly what exceptions are for - aborting the normal flow of code when something unexpected happens. So just move the "normal flow" code all inside the try block, and you won't need break (or continue) at all:

我猜你输入的最后一个突破是在输入无效时跳过returnChoiceOfChatbot(...)代码。但这正是异常所针对的 - 当意外发生时中止正常的代码流。因此,只需在try块中移动“正常流”代码,您就不需要中断(或继续):

while (true) {
    try {
        System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
        System.out.println("Typing other numbers will end the Chatbot");
        startup = userinput.nextInt();
        switch (startup) {
          // cases in here as before, omitted for brevity
        }
        String returningCode = returnChoiceOfChatbot(startup);
        System.out.println(returningCode);
    } catch (InputMismatchException e) {
        System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
    }
}

#1


2  

You need to replace the line break; with continue; in your catch block. You want to ask the user for a new input if it wasn't a number. Otherwise that break breaks the whole while loop and prevents it from running again. This said, it should read:

你需要更换换行符;继续;在你的拦截块中。如果用户不是数字,您想要询问用户输入新内容。否则该中断会破坏整个循环并阻止它再次运行。这说,它应该是:

    } catch (InputMismatchException e) {
        System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
        continue; // Jump back to the beginning of the while-loop
    }

Also check if you need to move these two lines:

还要检查是否需要移动这两行:

String returningCode = returnChoiceOfChatbot(startup);
System.out.println(returningCode);

outside of your while loop. While it's not clear to me what they are for, it looks like you might want to run them only once after the while loop was left.

在你的while循环之外。虽然我不清楚它们的用途,看起来你可能只想在while循环离开后运行它们一次。

#2


0  

} catch (InputMismatchException e) {
    System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
    break;
}

Just remove the break. It doesn't have anything to do with the catch specifically, just with the break that you wrote in it.

只需删除休息时间。它与捕获没有任何关系,只是与你在其中写的断点。

#3


0  

The break statement (when used without a label to specify what to break out of) will exit the nearest switch, while, for or do .. while loop.

break语句(在没有标签的情况下用于指定要突破的内容)将退出最近的开关,而for,for或while .. while循环。

You generally have to use it with switch as you do to stop the execution falling through to the next case - e.g. if you didn't have the breaks and the user selected 1, it would execute the code for all three cases, and then exit the program.

您通常必须将其与开关一起使用,以阻止执行进入下一种情况 - 例如如果你没有中断并且用户选择了1,它将执行所有三种情况的代码,然后退出程序。

Inside your catch block however, the break exits the while loop. Since the intention is to tell the user their input is invalid and then ask for new input, this isn't what you want to do here. You could change the break to a continue which would abort the current iteration of the while loop and start the loop again, however generally speaking this sort of flow control will make your program harder to follow and therefore maintain.

然而,在catch块内部,break会退出while循环。由于目的是告诉用户他们的输入无效然后请求新输入,这不是你想要做的。您可以将break更改为continue,这将中止while循环的当前迭代并再次启动循环,但一般来说,这种流控制将使您的程序更难以遵循并因此维护。

I'm guessing you put the last break in to skip over the returnChoiceOfChatbot(...) code when the input is invalid. But this is exactly what exceptions are for - aborting the normal flow of code when something unexpected happens. So just move the "normal flow" code all inside the try block, and you won't need break (or continue) at all:

我猜你输入的最后一个突破是在输入无效时跳过returnChoiceOfChatbot(...)代码。但这正是异常所针对的 - 当意外发生时中止正常的代码流。因此,只需在try块中移动“正常流”代码,您就不需要中断(或继续):

while (true) {
    try {
        System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
        System.out.println("Typing other numbers will end the Chatbot");
        startup = userinput.nextInt();
        switch (startup) {
          // cases in here as before, omitted for brevity
        }
        String returningCode = returnChoiceOfChatbot(startup);
        System.out.println(returningCode);
    } catch (InputMismatchException e) {
        System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
    }
}