I am having a little trouble with my homework.
I have to have a boolean isHigherGeneration() method that compares 2 CPU objects based on their generation.
I was able to make my code compare the 2 objects, but I need the result to return YES/NO instead of true/false.
I tried creating a string and transforming it into a boolean, but it didn't work. Can someone help me please?
Here is my code:
public boolean isHigherGeneration(CPU cpu){
String YES = "YES";
String NO = "NO";
boolean t = Boolean.valueOf(YES);
boolean n = Boolean.valueOf(NO);
if (this.generation > cpu.generation)
return t ;
else
return n;
}
Thank you in advance for your help :)
It sounds from the question like it doesn't want you to return a boolean
, but a String
with either the value YES
or the value NO
instead of a boolean
, so what you need to do is translate the result of the boolean
expression into a String
with the value YES
or the value NO
.
Thus, in this case, there's no need to play around with boolean
in your code. You can compare the CPU
generation and just return YES
if the value is true
and NO
if the value is false
:
public String isHigherGeneration(CPU cpu) {
if (generation > cpu.generation) {
return "YES";
} else {
return "NO";
}
}
Edit: From the sounds of the requirements, you need a boolean
method that returns String
, which is impossible. (That's like saying you want to buy an apple but end up with a pear.) If you do need a String
result and a boolean
method, you could divide them into three like this:
// Boolean method
public boolean isHigherGeneration(CPU cpu) {
return generation > cpu.generation;
}
// String method
public String toYesNo(boolean result) {
if (result) {
return "YES";
} else {
return "NO";
}
}
// Converter
public String isHigherGenerationYesNo(CPU cpu) {
return toYesNo(isHigherGeneration(cpu));
}
but this just all seems silly. I think maybe we're having a misunderstanding in the question. Could you post the question verbatim so that we can ensure that we've understood it correctly?