frozen_coyote
frozen_coyote

Reputation: 15

how to end a method in java through another method?

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.

Upvotes: 1

Views: 94

Answers (2)

Eric Guan
Eric Guan

Reputation: 15982

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
}

Upvotes: 1

Naman
Naman

Reputation: 31998

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.

Upvotes: 2

Related Questions