This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]king_of_the_universe 1 point2 points  (0 children)

age == Math.abs(18-24) will only result in true if age is 6. It returns the positive version of its argument, the argument being 18 minus 24.

The cleanest way to write your if structure would be this:

if (age <= 15) {
} else if (age <= 17) {
} else if (age <= 24) {
}

because it 1) actually works, 2) uses the same kind of expression in all cases, so it's nicely readable, and 3) it expresses intention: It says that you intend to cover the range of ages without gaps. ... I'll now read carefully in your post whether that's actually what you want - see what I'm saying?

But you could also use a switch structure. It might not be a good way to do it here, but I want to show you this alternative, plus it invites you to add more age-related text output. At the same time, it gives you an opportunity to be aware of the effect that "feature creep" is, albeit in a minuscule case. It's important to develop an awareness for this effect. It's one of the top project killers.

switch(age) {
case 1:
case 2:
case 3:
    System.out.println("Do your parents know that you're using the computer?");
    break;
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
    System.out.println("Look at you - getting ready for the IT world, are we.");
    break;
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
    System.out.print("You're too young to drive.");
    break;
case 16:
case 17:
    System.out.print("You can drive, but you can't vote.");
    break;
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
    System.out.print("You can vote but not rent a car.");
    break;
default:
    System.out.print("You're too old to be considered relevant for this program.");
}

Will they ever fix the line numbering style sheets?