I have written such a simple code:
I have written this line in my class's constructor :
List element = new ArrayList();
I have a variable named
cost
which its type isint
one method will return three lists with different objects:
listOne, listTwo, listThree
in another method I have written below code which this method will use those lists that are created in the method above.this method will be called three times for three lists above. each call for each list.
// beg开发者_如何学编程ining of the method: int cost = 0; if(cost==0){ element = listOne; cost = 3; } if(cost<4){ element = listtwo; cost = 6; } // end System.out.println(element.toString());
Unfortunately, instead of printing listTwo
it will print listThree
(if we have 4 or more lists it will print the last one)!
Is there any problem with if-else condition?
thanks
EDIT: this is my main code but its condition is like the code above:
auxiliaryList
in the code below is listOne
or list Two
or listThree
respectively.
cost = 0;
public void method {
System.out.println(element.toString());//number one
if (cost== 0) {
element = auxiliaryList;
cost = 3;
}
else if( cost<4){
element =auxiliaryList;
cost = 6;
}
}
return;
}
}
also the line which is declared with //number one
shows me that before going to the if/else condition ,the element list will be set to the current list in the method.
Is there any problem with if-else condition.
Yes - the problem is that you're not using if/else, you're just using two if statements.
Change the second if
to use an else
and it'll be fine:
if (cost == 0) {
element = listOne;
cost = 3;
} else if (cost < 4) {
element = listtwo;
cost = 6;
}
The problem was that if cost
was 0, it would enter the first block, set cost
to 3, and then go into the second block because 3 is less than 4. There was no "else" to stop that happening - the two if
blocks were entirely independent.
精彩评论