1

I am having a lot of problems with the if and else statements in Java. I am following this basic tutorial, but I’m using Eclipse since NetBeans with TMC doesn’t work for me.

What I am trying to do is 8.2 exercise 15 which is asking how old you are, and if you are over the age of 17, you are the age of majority, and if you are 17 or under, you are not.

Here is the program I currently have written:

import java.util.Scanner;

public class ifelse {
  public static void main (String args[]){
    Scanner reader = new Scanner(System.in);
    System.out.println("Enter your age: ");
    int num1 = 100;
    int num3 = 17;
    int num2 = Integer.parseInt(reader.nextLine());
    boolean isGreater = num1 > num3;
    boolean isLesser = num1 < num3;

    if (isLesser) {
      System.out.println("You have not reached the age of majority yet!");
    }

    if (isGreater) {
      System.out.println("You have reached the age of majority!");
    } else {
      System.out.println("You have not reached the age of majority yet!");
    }
  }
}

I was trying to mess around with booleans and different numbered ints etc., but I could not get it to work. Currently I can run the program but whatever I type ends up saying you have reached the age of majority.

I created the boolean isLesser and used it in the if statement, thinking that it would help, but it seems to overlook the first if statement or something.

I looked at the similar questions and ones that may have my answer but none of them have the exact same problem as me.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
FreezieX17
  • 45
  • 6

1 Answers1

0

Try to think of all the conditions that could be met before coding your if statements. In this case, there are 3...

if (num2 < num3)
{ 
  //less than the age of majority
}
else if (num 2 > num3)
{
  //greater than the age of majority
}
else if (num2 == num3)
{
  //less than the age of majority
}

Alternatively, we could make this much simpler:

if (num2 > num3)
{
  // greater than the age of majority
}
else
{
  // less than the age of majority
}
Eric
  • 601
  • 7
  • 22
  • What happens if I enter 17? – Eric Dec 12 '16 at 01:53
  • If you enter 17 you should not be the age of majority, at least in my coding. I'm not sure if you meant that as a rhetorical question or a legitimate one – FreezieX17 Dec 12 '16 at 01:56
  • No problem. If you found my answer helpful, please consider clicking the checkmark on the left of the page. Cheers! – Eric Dec 12 '16 at 03:38