Reputation: 13
I am trying to convert an excel nested IF statement into code language, but I am not sure if I am doing it correctly and was hoping I could get some help
Here is the excel statement :
=IF(D3="Feather",IF(OR(I3>1000,R3="n/a"),"",IF(W3="F","F",IF(AND(I3<=1000,R3>8),"F","P"))),"")
My code :
if( D3 == "Feature"){
if (I3>1000 || R3 =="n/a") {
} else if (W3=="F"){
"F"
} else if( I3<=1000 && R3>8){
"F"
} else {
"P"
}
}
Thank you
Upvotes: 0
Views: 1539
Reputation: 79807
You have indeed interpreted the Excel formula correctly, but there are three things that stop your code from being "correct Java".
"P"
, "F"
and so on don't really have any effect sitting by themselves between {
and }
. The thing about the Excel formula is that it actually has a value; and that's something that a series of Java if
and else
statements don't actually have. If you want a value, you could either write all of this as a Java method that returns a value, or you could use the ternary operator ? :
to create a single expression with the value that you desire.equals
method, instead of the ==
operator. The reason is that two different String
objects might have the same value; but in this case, ==
will return false
for them, but equals
will return true.R3
is. At one point, you treat it as if its type were String
, and at another point, you treat it as a numeric variable. Unlike Excel formulas, any expression in Java has a well defined data type.Translating the formula into a Java expression, and being careful of these three issues, we get something like this.
d3.equals("Feather") ?
((i3 > 1000 || r3.equals("n/a")) ? "" :
w3.equals("F") ? "F" :
(i3 <= 1000 && Integer.parseInt(r3) > 8) ? "F" : "P" ) : ""
But this is a bit hard to read, because there are too many ternary operators. Most people would prefer to write this as a method, something like this.
public String excelFormula(String d3, int i3, String r3, String w3) {
if (d3.equals("Feather")) {
if (i3 > 1000 || r3.equals("n/a")) {
return "";
} else if (w3.equals("F")) {
return "F";
} else if (i3 <= 1000 && Integer.parseInt(r3) > 8) {
return "F";
} else {
return "P";
}
} else {
return "";
}
}
Upvotes: 1