I have been working with Java for a little more than a year. I recently have built a Tic Tac Toe game as an assignment for my Java class. After my instructor graded it, he wrote a comment around my validation method logic. Even though I got 100%, he said that the logic in my validation method is too cumbersome. He stated that I should look into a for or
while` statement in order to clean out some code in my validation method.
Is there really a way to put all my conditional if
statements in to a for
or while
loop? And if so, I would like to know what logic goes behind that. This program had a set of five arrays but in this validation method I worked only with the JButton
array.
JButton [] button = new JButton [9];
public void validate()
{
if(button[0].getText().equals(button[1].getText()) && button[1].getText().equals(button[2].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText());
gameOver();
return;
}
else if(button[3].getText().equals(button[4].getText()) && button[4].getText().equals(button[5].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[3].getText());
gameOver();
return;
}
else if(button[6].getText().equals(button[7].getText()) && button[7].getText().equals(button[8].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[6].getText());
gameOver();
return;
}
else if(button[0].getText().equals(button[3].getText()) && button[3].getText().equals(button[6].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText());
gameOver();
return;
}
else if(button[1].getText().equals(button[4].getText()) && button[4].getText().equals(button[7].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[1].getText());
gameOver();
return;
}
else if(button[1].getText().equals(button[4].getText()) && button[4].getText().equals(button[7].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[1].getText());
gameOver();
return;
}
else if(button[2].getText().equals(button[5].getText()) && button[5].getText().equals(button[8].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[2].getText());
gameOver();
return;
}
else if(button[0].getText().equals(button[4].getText()) && button[4].getText().equals(button[8].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText());
gameOver();
return;
}
else if(button[2].getText().equals(button[4].getText()) && button[4].getText().equals(button[6].getText()))
{
JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[2].getText());
gameOver();
return;
}
int i;
for(i=0;i<button.length;i++)
{
if(button[i].isEnabled())
{
break;
}
}
if(i == button.length)
{
JOptionPane.showMessageDialog(null,"This was a Draw");
}
}