Reputation: 1
Write a function in Java that implements the following logic: Your cell phone rings. Return true if you should answer it. Normally you answer, except in the morning you only answer if it is your mom calling. In all cases, if you are asleep, you do not answer.
public boolean answerCell(boolean isMorning, boolean isMom, boolean isAsleep)
{
if (isMom && isMorning && isAsleep)
{
return false;
}
if ((!isMom) && isMorning && isAsleep)
{
return false;
}
if (isMorning && isMom && (!isAsleep))
{
return true;
}
if ((!isMorning) && isMom && isAsleep)
{
return false;
}
else
{
return true;
}
}
For the code that I have written above, I am only getting 63% problem coverage and I can't figure out why. The feedback that I am receiving is saying that (False, false, true) was true but I was expecting false. and (true, false, false) was true but its also expected to be false.
Upvotes: 0
Views: 1466
Reputation: 1
public boolean answerCell(boolean isMorning, boolean isMom, boolean isAsleep) {
if(isAsleep==true)
{
return false;
}
else if( (isMorning ==false) && (isMom==false) && (isAsleep==false))
{
return true;
}
else if( (isMorning ==true) && ((isMom==true) ))
{
return true;
}
else if( (isMorning ==true) && ((isMom==false) ||(isAsleep==false)))
{
return false;
}
else
{
return true;
}
}
Upvotes: 0
Reputation: 774
Simplifying if statements
This is the detailed Method so you can understand what is supposed to do:
public boolean answerCell(boolean isMorning, boolean isMom, boolean isAsleep){
if(isAsleep){
return false;
}else{
if(isMorning){
if(isMom){
return true;
}else{
return false;
}
}else{
return true;
}
}
}
But here is what you can do with one line If statement:
public boolean answerCell(boolean isMorning, boolean isMom, boolean isAsleep){
return isAsleep?false:isMorning?isMom:true;
}
If you need more information about the one line if statement you can check out this resource, although there is a lot of information on the web.
Upvotes: 3
Reputation: 23634
Try not to break out all of the conditions into a single statement. Take the problem one step at a time.
Normally you answer,
return true;
except in the morning you only answer if it is your mom calling.
if (isMorning) {
if (isMom) {
return true;
}
else {
return false;
}
}
return true;
In all cases, if you are asleep, you do not answer.
if (isAsleep) {
return false;
}
if (isMorning) {
if (isMom) {
return true;
}
else {
return false;
}
}
return true;
Upvotes: 0