1

I'm starting to learn about boolean expressions. I am trying to figure out the following question:

Suppose age1, age2, and age3 are int variables, and suppose answer is a boolean variable. Write an expression that assigns answer the value true exactly when age1 is less than or equal to age2 AND age2 is less than or equal to age3. Otherwise answer should be assigned false.

I have tried a few things but am relatively new to Java. I am able to make the answer print True but something is still wrong with my numbers.

This is wrong:

age1=7;
age2=10;
age3=12;
boolean a= (age1<=age2);
boolean b= (age2<=age3);
boolean answer= (a&&b);

I'm just not sure how to fix this or what exactly is going on in the code; what am I doing wrong?

8
  • 6
    What makes you think it's wrong? Commented Feb 16, 2015 at 16:16
  • I am using an online learning website for my college. When I enter that code it says I'm wrong. The following feedback pops up: Feedback: Your code failed for age1=5, age2=7, and age3=2 Commented Feb 16, 2015 at 16:19
  • Maybe it just thinks you didn't declare ages as ints Commented Feb 16, 2015 at 16:20
  • 2
    Perhaps it is wrong format. Maybe it doesn't like the two extra variables, a and b. To avoid using those, you can do boolean answer = age1 <= age2 && age2 <= age3; Commented Feb 16, 2015 at 16:21
  • 2
    Or, since it says "write an expression", it might just want the expression, in which case just input age1 <= age2 && age2 <= age3. Or boolean answer = age1 <= age2 && age2 <= age3; Commented Feb 16, 2015 at 16:22

1 Answer 1

3

The code your given should work perfectly.

age1=7;
age2=10;
age3=12;
boolean a= (age1<=age2);
boolean b= (age2<=age3);
boolean answer= (a&&b);

But as the questions specifies an "expression" try this out:

boolean answer=age1<=age2 && age2<=age3;
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, you can leave the brackets out.
@MinecraftShamrock oops ! edited my answer , but shouldnt it work with the brackets also?
@MohitBhasi Sure, it works with and without brackets. But they are optional here because <= has a higher precedence than &&. See Java Precedence Table
@MinecraftShamrock oo yea! completely forgot about the precedence :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.