I have a section of code that changes the value of a parameter based on the desired input and output that has been chosen. So in the below example, I calculate the volume of a sphere then depending on the units the user used for the input and the units the user chose for the output the number is manipulated accordingly.
My problem is that all my if statements are returning false and the number 10 (from the else) is coming through regardless of what is chosen. I have printed out the value of inputPref and outputPref and they look exactly equal to “mm” and “cubic cm” (for example) and yet still won’t be captured by the if statements.
Any obvious errors? The two variables “inputPref” and “outputPref” are loaded from shared preferences if that helps!
double volumeBase = 4 * piDouble * radius * radius * radius / 3;
double volume;
if(inputPref.equals("mm") || outputPref.equals("cubic cm"))
{
volume = volumeBase / 1000;
}
if(inputPref.equals("mm") || outputPref.equals("cubic metres"))
{
volume = volumeBase / 1000000000;
}
if(inputPref.equals("cm") || outputPref.equals("cubic mm"))
{
volume = volumeBase * 1000;
}
if(inputPref.equals("cm") || outputPref.equals("cubic metres"))
{
volume = volumeBase / 1000000;
}
if(inputPref.equals("metres") || outputPref.equals("cubic mm"))
{
volume = volumeBase * 1000000000;
}
if(inputPref.equals("metres") || outputPref.equals("cubic cm"))
{
volume = volumeBase * 1000000;
}
else
{
volume = 10;
}
All your
ifstatements (except the first one) should beelse ifstatements, so that it only chooses 1 out of all your options.As it stands, your code may be evaluating an
ifstatement early on, but it is getting overwritten by the lastif-elseat the very end, which is almost always going to return10.As pointed out in the comments, you’re probably also meaning to use
&&instead of||so that you’re running the code when both conditions match in eachiforelse ifstatement. You might also consider usingequalsIgnoreCase()instead ofequals(), so that the case of the users input doesn’t matter.It should be…
If it still isn’t working, it might be a problem with the code where you’re reading the user input.