Java 在 switch 语句中抛出异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20216722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:22:25  来源:igfitidea点击:

Throw exception in switch statement

javaexceptionswitch-statement

提问by masmic

This program is something simplified to what we would find in a music store. We enter the comand we want and it makes what that comand supposes to do. These are the options.

这个程序被简化为我们在音乐商店中可以找到的程序。我们输入我们想要的命令,它会执行该命令应该执行的操作。这些是选项。

  • Create "client"|"music"|"selling"

  • List "client"|"music"|"selling"

  • Erase "client"|"music"|"selling" (using, or without using a code that is generated when we create new statement)

  • 创建“客户”|“音乐”|“销售

  • 列出“客户”|“音乐”|“销售

  • 擦除“客户端”|“音乐”|“销售”(使用或不使用我们创建新语句时生成的代码)

The program must execute until we type "close".

程序必须执行,直到我们键入“close”。

Here I'm posting what I've done until now.

在这里,我发布我到目前为止所做的事情。

The main question is how to throw a exception if we type wrong a comand or we type something that doesn't exist here. Now, wen this occurs it just goes back to the begining. I would apreciate too if you give me advices on any change or modification that you think could be better for the program, I'm just starting with this and I know this could be done in a better way:

主要问题是如果我们输入错误的命令或我们输入的东西在这里不存在,如何抛出异常。现在,一旦发生这种情况,它就会回到起点。如果您就您认为可能对程序更好的任何更改或修改向我提出建议,我也将不胜感激,我只是从这个开始,我知道这可以以更好的方式完成:

public class Main {

    static GestionarMusica musiclist= new GestionarMusica(20);
    static GestionarCliente clientlist= new GestionarCliente(20);

    static Scanner input= new Scanner(System.in);
    static String instructions;

    public static void main (String[] args){

    do{
        try{
            System.out.println("Waiting for instructions: ");
            instructions= input.nextLine();

            switch (instructions){
                case "create client":
                    createClient();
                    break;
                case "create music":
                    createMusic();
                    break;
                case "create selling":
                    //createSelling();
                    break;

                case "list client":
                    listClient();
                    break;
                case "list music":
                    listMusic();
                    break;
                case "list selling":
                    //listSelling();
                    break;
            }
        }catch (NullPointerException npe){
            System.out.println("There are not articles on the list");
        }

        if (instructions.equals("erase client")){
            eraseClientWithoutCode();
        }
        if (instructions.length() <= 18 && instructions.length() >= 17 && instructions.substring(0, 16).equals("erase client")){
            String client_code = instructions.substring(16);
            client_code = client_code.trim();
            int code = Integer.parseInt(client_code);
            eraseClientWithCode(code);
        }

        if (instruction.equals("erase music")){
            eraseMusicWithoutCode();
        }
        if (instructions.length() <= 17 && instructions.length() >= 16 && instructions.substring(0, 15).equals("erase music")){
            String music_code = instructions.substring(15);
            music_code = music_code.trim();
            int code = Integer.parseInt(music_code);
            eraseMusicWithCode(code);
        }

        if (instructions.equals("erase selling")){
            eraseSellingWithoutCode();
        }
        if (instructions.length() <= 16 && instructions.length() >= 15 && instructions.substring(0, 14).equals("erase selling")){
            String selling_code = instructions.substring(14);
            selling_code = selling_code.trim();
            int code = Integer.parseInt(selling_code);
            eraseSellingWithCode(code);
        }

    }while(!instructions.equals("close"));
}


public static void createMusic() {
    System.out.println("Insert album title: ");
    String title = teclado.nextLine();
    System.out.println("Insert album autor: ");
    String autor = teclado.nextLine();
    System.out.println("Insert format: ");
    String format = input.nextLine();

    musiclist.add(new Music(title, autor, format, musiclist.generateCode()));
}

public static void listMusic() {
    System.out.println(musiclist.toString());
}

public static void eraseMusicWithCode(int code) {
    musiclist.delete(code);
    System.out.println("Article deleted");
}

public static void eraseMusicWithoutCode() {
    System.out.println("Insert article code: ");
    int code = input.nextInt();
    musiclist.delete(code);
    System.out.println("Article deleted");
}

UPDATE-- About the use of default in the switch statement

UPDATE--关于switch语句中default的使用

I cannot use the default because this reason. Inside the switch I have the createand listcommands, but I have had to set the erasecommands outside the witch because these depends on if I enter the command with the code, or without it. So, if I enter an erase command and if I have the default inside the switch, it will show the exception.

因为这个原因,我不能使用默认值。在开关内部,我有创建列表命令,但我必须在女巫之外设置擦除命令,因为这取决于我输入的命令是否带有代码。所以,如果我输入一个擦除命令并且我在开关中有默认值,它将显示异常。

采纳答案by user987339

If you want to use switch/caseadd defaultfor handling unknown commands. You don't need any exception for this. Just handle wrong input properly. So you will have to preparse input and determine if those are cases with three arguments. Move the code for special cases inside switch/caseand check 3rd parameter. I make it for one case so you can get idea. So with default, a bit dirty, not testedcode will be:

如果您想使用switch/caseadddefault来处理未知命令。你不需要任何例外。只要正确处理错误的输入。因此,您必须预先解析输入并确定这些是否是具有三个参数的情况。移动内部特殊情况的代码switch/case并检查第三个参数。我做了一个案例,所以你可以得到想法。因此,默认情况下,有点脏,未测试的代码将是:

    public static void main (String[] args){

    do{
        try{
            System.out.println("Waiting for instructions: ");
            instructions= input.nextLine();
        String preparsedInstructions = instructions;
        int from = instructions.indexOf(" ");
        if(from > -1){
            int to = preparsedInstructions.indexOf(" ", from + 1);
            if(to > -1){
                preparsedInstructions = preparsedInstructions.substring(0, to);
            }
        }

            switch (preparsedInstructions){
                case "create client":
                    createClient();
                    break;
                case "create music":
                    createMusic();
                    break;
                case "create selling":
                    //createSelling();
                    break;

                case "list client":
                    listClient();
                    break;
                case "list music":
                    listMusic();
                    break;
                case "list selling":
                    //listSelling();
                    break;
                case "erase client":
            if (instructions.length() <= 18 && instructions.length() >= 17 && instructions.substring(0, 16).equals("erase client")){
                String client_code = instructions.substring(16);
                client_code = client_code.trim();
                int code = Integer.parseInt(client_code);
                eraseClientWithCode(code);
            }else{
                    eraseClientWithoutCode();
            }
                    break;
        ...//do for erase music,selling

        default: //error handling
            }
        }catch (NullPointerException npe){
            System.out.println("There are not articles on the list");
        }



    }while(!instructions.equals("close"));
}

回答by Ivaylo Strandjev

You can add a default:case in which you handle something else being input. The statement in default:is executed if the value if not any of the listed options. I believe switch's documentationshows well how to do that.

您可以添加一个default:案例来处理正在输入的其他内容。default:如果值不是列出的任何选项,则执行in 语句。我相信switch 的文档很好地展示了如何做到这一点。

回答by Satheesh Cheveri

Just to simplify

只是为了简化

        case "list selling":
                //listSelling();
                break;

        default:
            if(instructions.equals("erase music") || instructions.equals("erase client") ){
                System.out.println("hello delete");
                //do your operation
            }
            else{
                System.out.println("hello default throw exceliotn");
                throw new RuntimeException("Invalid entry");

            }
        }

You may effectively move the ifclause in to a method and you can return 'boolean flag' to determine to throw exception or not . This will increase the readability.

您可以有效地将if子句移动到方法中,并且您可以返回“布尔标志”以确定是否抛出异常。这将增加可读性。