有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何通过另一个方法结束java中的一个方法?

这是我的代码:

public  boolean isConsonant(char x){
        if (!Character.isLetter(x)){
            System.out.print ("What you have entered cannot be a consonant or vowel.");
            return false;
        }
        return (x != 'a' && x != 'e' && x != 'i' && x != 'o' && x != 'u');
    }

我遇到的问题是第一个if语句。在此之后,我在代码中多次调用isconsant方法,并根据返回值(true或false)执行一些操作

问题是,如果char不是字母,我根本不希望该方法继续。我希望节目结束。我试着写另一个方法,看起来像这样:

public voidisNotLetter(char x)
     if (!Character.isLetter(x){
          System.out.println("What you have entered cannot be a consonant or vowel."); 
}

这就是我被困的地方。我不知道我能在这个方法里放些什么来阻止程序运行,然后直接把那个语句打印给用户。我曾想过抛出一个IllegalArgumentException,但从技术上讲这不是真的,因为这个论点是有效的,但这不是我想要的


共 (2) 个答案

  1. # 1 楼答案

    如果您想“停止程序运行,只需将该语句打印给用户”,这可能会有所帮助:

    if (!Character.isLetter(x)){
        System.out.print ("What you have entered cannot be a consonant or vowel.");
        System.exit(0); //This would terminate the execution if the condition is met
     }
    

    更多细节here。希望有帮助

  2. # 2 楼答案

    可以尝试嵌套if语句

    if(isLetter(input)){
        if(isConsonant(input)
            //input is consonant
        else
            //input is not consonant
    }else{
        //input is not letter
    }