-3

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.

3 Answers3

1

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");
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

You can use a simple else if the above condition is not true it will directly give the output or you can use else if too.. In line 7 there should be println...

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 26 '23 at 11:16
0

The content that follows the if-conditional statement, within the brackets, { }, is called a scope—also referred to as a code-block.

A matching conditional statement will enter the scope, whereas a failing conditional statement will skip to after the scope.

Thus, testing for verify >= 18 will determine whether the scope code will be executed or not.

So, when verify is below 18, the program will skip to after the scope, and, in this case, exit the program.

You'll need to move the inner if-conditional, to outside of it's current scope.

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

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

Here is a documentation on if-conditional statements, by Java.
The if-then and if-then-else Statements (The Java™ Tutorials > Learning the Java Language > Language Basics).

Additionally, here is a Wikipedia article on control-flow, the term used for data mitigation—e.g., if-statements.
Wikipedia – Control flow.

Reilas
  • 3,297
  • 2
  • 4
  • 17