2016-02-26 87 views
1

这里是我的代码:如何通过另一种方法在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语句。我之后在代码中多次调用isConsonant方法,并根据返回值(true或false),代码执行一些操作。

问题是如果字符不是字母,我不希望方法继续。我希望程序结束。我试图做的是写另一种看起来像这样的方法:

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

这就是我卡住的地方。我不知道我可以使用哪种方法停止程序运行,只需将该语句输出给用户。我想抛出一个IllegalArgumentException,但这在技术上并不真实,因为参数是有效的,但不是我想要的。

+0

也许你应该做别的事情而不是停止它,因为你不能停止运行直到结束或返回一些价值。 – TomN

回答

2

如果你想“停止运行程序,只是打印语句用户”,这可能帮助:

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。希望能帮助到你。

+0

谢谢你,这个伎俩。非常感激, –

1

您可以尝试嵌套if语句。

if(isLetter(input)){ 
    if(isConsonant(input) 
     //input is consonant 
    else 
     //input is not consonant 
}else{ 
    //input is not letter 
} 
相关问题