This is my task, and I'm trying to do that with the short if-statements only, the only error I get is that with the syntax where there's "(0.5<=ratio<2)", other than that, Is the construction right?
Scanner scn = new Scanner(System.in);
int years,kg,cm,MenuA,MenuB,MenuC,A,B,C;
String not;
double ratio = cm/kg;
System.out.println("Please enter your age (years), weight(kg) and height(cm) in that order with spaces");
years = scn.nextInt();
kg = scn.nextInt();
cm = scn.nextInt();
MenuA = (20<years<<11||40<<years<21)&&(0.5<=ratio<2)?A:MenuB;
MenuB = (20<years<<11)&&(2<=ratio<<3.5)?B:MenuC;
MenuC = (40<<years<21)&&(2<=ratio<<3.5)?C:not;
}
}
20 < years < 11
That's not valid Java code. No matter which of the operands you evaluate first, the result will be of type boolean
which does not compare to int
.
You'll need to do it the long way:
20 < years && years < 11
Or create a method for this:
betweenExclude(20, years, 11);
with
boolean betweenExclude(int a, int b, int c) {
return a < b && b < c;
}
and maybe also
boolean betweenIncludeLeft(double left, double number, double right) {
return left <= number && number < right;
}
In terms of readability / maintainability you should also consider writing this in a way, that is easily translated into your table:
enum Age {
ELEVEN_TO_TWENTY,
TWENTYONE_TO_FORTY
};
Age age;
if(between(11, years, 20)) {
age = Age.ELEVEN_TO_TWENTY;
}
if(between(21, years, 40)) {
age = Age.TWENTYONE_TO_FORTY;
}
Similar for the weight to height ratio
And later
if(age.euqals(Age.TWENTYONE_TO_FORTY) && weightratio.equals(WeightRatio.LOW)) {
//A
}
Comment
Your age-check should include both your boundaries. 11 and 20 have to be in, otherwise people of age 10 and 11 will drop out.