0

Hi guys i currently have a assignment which i just finished but their is one detail i dont love about it. Is there a way to shorten if else loops

Currently i have wrote

    if (x >=300) {
        set y = 1;
    }
    else if(x >=200) {
        set y = 2;
    }
    else if (x >=150) {
        set y = 3;
    }
    else if (x>=100) {
        set y = 4;
    }
    else if (x >=50) {
        set y = 5;
    }
    else if (x >=25) {
        set y = 6;
    }

Probably me just being pedantic, thanks in advance

AWGAL
  • 157
  • 1
  • 2
  • 12
  • 2
    Related: https://stackoverflow.com/questions/28892969/java-switch-statement-with-range-of-int/45446005#45446005 – MC Emperor Oct 01 '19 at 21:21
  • there are ways to shorten them. The question is why? every shortened version is less readable, IMO - what you have now seems ok. However, your `set u = 3;` is not really java, maybe you really have some bigger block of code there, and should that be optimized instead? – eis Oct 04 '19 at 06:18
  • I have more code using a setter and getter system so its like setSize = 3; I feel i have optimised the rest of my code just the if/else seemed long, i guess its the best way for readability which is fine. I just wished to see other ways for my own learning if there was one – AWGAL Oct 05 '19 at 08:03

2 Answers2

0

You could shorten it to

y = x>=300 ? 1 : x>=200 ? 2 : x>=150 ? 3 : x>=100 ? 4 : x>=50 ? 5 : 6;

but while that may be more compact, it is also subjectively less readable. For additional informatione, see here.

Dennis B.
  • 118
  • 6
0

This looks like a place where you could use the switch statement. However, the switch statement is designed to handle known values rather than inequalities. If you don't like the way the chain of if-else statements looks, you could do it all in an inline expression (Ternary Operator), but that makes it hard to read.

I'd say keep the code the way it is unless there's a good reason to change it. If you're only going to have one code statement after each statement, then you can eliminate the curly braces {} to make the code look a little cleaner:

    if (x >= 300) set y = 1;
    else if (x >= 200) set y = 2;
    else if (x >= 150) set y = 3;
    else if (x >= 100) set y = 4;
    else if (x >= 50) set y = 5;
    else if (x >= 25) set y = 6;
Jaeheon Shim
  • 491
  • 5
  • 14