I’m working on some beginning Java logic, and I’m not sure why this is not working. Here is a method I made:
private void printSubclassBoxes(){
int coordinateX = ((getWidth() - BOX_WIDTH) /4);
for ( int i = 0; i < 3; i++){
double coordinateY = (getHeight() / 2);
GRect classBox = new GRect (coordinateX, coordinateY, BOX_WIDTH, BOX_HEIGHT);
GLabel classLabel = new GLabel ("Program");
double labelCoordinateX = (coordinateX + ((classBox.getWidth() / 2) - (classLabel.getWidth() / 2)));
double labelCoordinateY = (coordinateY + ((classBox.getHeight() / 2) + (classLabel.getAscent() / 2)));
add(classBox);
add(classLabel, labelCoordinateX, labelCoordinateY);
if (i == 1){
coordinateX = (((getWidth() - BOX_WIDTH) /4) * 2);
}
if (i == 2){
coordinateX = (((getWidth() - BOX_WIDTH) /4) * 3);
}
}
}
Now I’m sure there are probably better ways to do this, but please-I’m not interested in that right now (I’m trying to learn without being spoonfed the answers). All I am wanting to know is why the ending two if statements are not working like I think they should.
For simplicity sake, let’s say
100 = ((getWidth() - BOX_WIDTH)
int coordinateX = 25;
My understanding is that int i gets to that first if statement and adds 25 + 25 so then coordinateX = 50.
then next time in the loop, i = 2 so coordinateX would = 75.
This is what I’m expecting to happen, but it’s not. I seem to be printing the first two boxes directly on top of each other, and then the third is moving 25.
Thanks for your help guys. Now that I got that loop figured out, I went ahead and solved it a different way. I ended up assigning coordinateX to another variable and using that to add to the end:
int coordinateX = ((getWidth() - BOX_WIDTH) /4);
int otherCoordinateX = coordinateX;
for ( int i = 0; i < 3; i++){
double coordinateY = (getHeight() / 2);
GRect classBox = new GRect (coordinateX, coordinateY, BOX_WIDTH, BOX_HEIGHT);
GLabel classLabel = new GLabel ("Program");
double labelCoordinateX = (coordinateX + ((classBox.getWidth() / 2) - (classLabel.getWidth() / 2)));
double labelCoordinateY = (coordinateY + ((classBox.getHeight() / 2) + (classLabel.getAscent() / 2)));
add(classBox);
add(classLabel, labelCoordinateX, labelCoordinateY);
coordinateX = otherCoordinateX + coordinateX;
}
at the first iteration of the loop:
i = 0, andcoordinateX = 25, as expected.At the end of the iteration
coordinateXis not updated (sincei == 0).Then, at the second iteration:
i = 1,coordinateX = 25since it wasn’t updated.At the end of the second iteration
coordinateXis updated because of theif i == 1)test.In the third iteration
i = 2coordinateXis used, which was set at the end of the second iteration.Solution
To not change your code in any essential way, simply replace
if (i == 1)byif (i == 0), andif (i == 2)byif (i == 1).EDIT: Lesson
In the
for(...) { } declaration, thei < 3test is checked at the beginning of each iteration, but thei++part is called at the end of each iteration.