Quantcast
Channel: User raptortech97 - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 22

Answer by raptortech97 for Tic Tac Toe game in Java OOP

$
0
0

Mathew had some great responses, but I'd like to explain a little more about using for loops. If you take a look at your Board() code right now, you might notice how a lot of the code is the same - when you make the JButtons, for example, you call new JButton("") nine times in a row. In general, having a lot of code that all looks the same or is copy-pasted is a bad idea. You can use a for loop with an array to clean this up a lot. Here's how Board() would look after using an array.

Board() {    // creates the panel    setLayout(new GridLayout(3, 3));    buttons = new JButton[9];    for (int i=0; i < buttons.length; i++) {        buttons[i] = new JButton("");    }    SetGame();    for (int i=0; i < buttons.length; i++) {        add(buttons[i]);            buttons[i].addActionListener(this);    }    }

See how much shorter and less repetitive that is?

As a side note, by not specifying 'public' or 'private', you implicitly made your constructors package-private, which is rarely the right solution. I recommend specifying everything as either public or private, until you get to the point of distributing your code or compiled programs, in which case package-private might occasionally make sense.


Viewing all articles
Browse latest Browse all 22

Trending Articles