The below code is extraction from a Java program. The program code is very big so I am just posting the needed part. In the code, what does the if (i == 2) do? What does it check, and how can it check for 2?
panel.setLayout(new GridLayout(5, 4, 5, 5));
String[] buttons = {
"Cls", "Bck", "", "Close", "7", "8", "9", "/", "4",
"5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"
};
for (int i = 0; i < buttons.length; i++) {
if (i == 2)
panel.add(new JLabel(buttons[i]));
else
panel.add(new JButton(buttons[i]));
}
Given the line:
The
forstatement creates the variableiat value0. Then it runs the code between{and}one time for each value in the arraybuttons(a list structure), increasing the variableifor each time.The first time through, the line
if (i == 2)will fail, becauseiis still0, and then calling the code after theelsestatement. This adds a button with the textCls.The third time through the code the variable
iwill be2(because it started at zero), and then it will run the line afterif (i == 2)– because that is what it does.It will then add a an empty label (the third entry in the array
buttons, arrays start at0for the first position.) instead of a button.I suggest having a look at the Java tutorials for more information on the language and structures of it. 🙂