0

I'm required to set a max value for a variable to 100:

double area = length * width;       
if (area > 100) { //set parameters for area    
    area = 100;
}

How can I code this in a way that works and doesn't require the use of 'if statement'?

2
  • 3
    What exactly is the problem with an if statement? Commented Aug 13, 2017 at 6:06
  • Nothing. Exercise asks specifically to not use if statement. Commented Aug 13, 2017 at 6:25

3 Answers 3

2
double area = Math.min(length * width, 100);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. this was exactly what I was looking for. We aren't allowed to use if statements yet because we haven't started studying it yet I guess.
I should give you fair warning, given that this is for an assignment: if you're not allowed to use if statements because you haven't learned them yet, I cannot guarantee you'd be allowed to use this either for the same reason.
We have covered Math, Scanner etc so it's fine. I'll double check to make sure though. Thanks.
2

You could try using Math.min, although I personally think it's less clear.

area = Math.min(area, 100);

1 Comment

It's a common enough idiom, though, that it will be clear to most readers.
2

A ternary operator would work too:

double area = length * width;
area = area > 100.0? 100.0 : area;

If you don't mind calculating area twice, you can shorten this to a single line:

double area = (length * width) > 100.0 ? 100.0 : (length * width);

Comments

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.