javanested-if

How do I print if someone is or not eligible to vote by using nested if statement?


I'm trying to print simple lines of text using nested if statement. but somehow relational symbols return an always false:

//unfinished
import java.util.Scanner;
public class exe6 {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your age for verification: ");
        int verify = sc.nextInt();

        if (verify >= 18){
            System.out.println("You are eligible to vote.");
            if (verify <= 17) {                                    //always false
                System.out.println("Minors are ineligible to vote");
            }
        }
    }
}

I think my brain is not braining and my logic has some problems. please show me the way.


Solution

  • You should just use an else. If verify >= 18 is false, then verify is necessarily less than or equal to 17, so you don't need to write the condition again. Nesting is also incorrect here because the inner if statement will only be run if the first condition was true, i.e. verify is at least 18 (and thus is never <= 17).

    if (verify >= 18) {
        System.out.println("You are eligible to vote.");
    } else {
        System.out.println("Minors are ineligible to vote");
    }