1

Here's my code:

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');
    }

The problem I'm having is the first if statement. I call the isConsonant method multiple times in the code after this and depending on the return calue (true or false) the code does some action.

The problem is that I don't want the method to continue at all if the char isn't a letter. I want the program to end. What I tried to do is write another method that looked like this:

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

This is where I'm stuck. I don't know what I can put in that method that will stop the program from running and just print that statement to the user. I thought about throwing an IllegalArgumentException, but that's not technically true since the argument is valid but just isn't what I want.

  • maybe you should do something else instead of stop it, because you can't stop running until end or return some value. – TomN Feb 26 '16 at 04:05

2 Answers2

2

If you want to "stop the program from running and just print that statement to the user", this might help :

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
 }

More details here. Hope it helps.

Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353
1

You can try nesting if statements.

if(isLetter(input)){
    if(isConsonant(input)
        //input is consonant
    else
        //input is not consonant
}else{
    //input is not letter
}
Eric Guan
  • 15,474
  • 8
  • 50
  • 61