Ok guys...I'm stumped again.
I managed to get the game working. However, now I'm down to the point of trying to code the win conditions. I'm thinking of using a boolean array for each of the buttons, but can't figure out how to cross reference the buttons[] to the gameSquares[] to set the elements of gameSquares[] to true/false flags.
Any pointers? (Code is copied below).
** A few other interesting bugs I feel worth mentioning:
1) Start and Reset don't seem to work correctly
2) When the computer tries multiple attempts in invalid squares, the squares seem to jump or dance around. It's really weird.
package tictactoegame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class TicTacToeBoard extends JFrame implements ActionListener
{
JButton[] buttons = new JButton[10];
boolean player1 = false, player2 = false;
boolean[] gameSquares = {false, false, false,
false, false, false,
false, false, false};
boolean startPlayer = false;
int turnCount = 0;
public TicTacToeBoard()
{
JFrame gameWindow = new JFrame();
gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
gameWindow.setSize(300,400);
gameWindow.setVisible(true);
JPanel gamePanel = new JPanel();
gamePanel.setSize(300,400);
GridLayout grid = new GridLayout(4,3);
gamePanel.setLayout(grid);
for(int i = 0; i < 9; i++)
{
buttons[i] = new JButton("");
buttons[i].addActionListener(this);
gamePanel.add(buttons[i]);
}
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
JButton helpButton = new JButton("Help");
helpButton.addActionListener(this);
gamePanel.add(startButton);
gamePanel.add(helpButton);
gamePanel.add(resetButton);
gameWindow.add(gamePanel);
gameWindow.pack();
while (turnCount < 9)
{
gamePlay();
}
}
public void gamePlay()
{
while(!startPlayer)
{
int random = randomGenerator();
if (random%2 == 0)
{
player1 = true;
JOptionPane.showMessageDialog(null, "Player is first.");
startPlayer = true;
}
else if (random%2 == 1)
{
player2 = true;
JOptionPane.showMessageDialog(null, "Computer is first.");
startPlayer = true;
}
}
if (player2)
{
int index;
Random randomGenerator = new Random();
index = randomGenerator.nextInt(9);
buttons[index].doClick();
player2 = false;
player1 = true;
}
}
public int randomGenerator()
{
int randomNum;
Random randomGenerator = new Random();
randomNum = randomGenerator.nextInt(100);
return randomNum;
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source instanceof JButton)
{
JButton button = (JButton) source;
if (button.getText() == "Start")
{
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Reset")
{
for(int i = 0; i < 9; i++)
{
buttons[i].setText("");
}
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Help")
{
JOptionPane.showMessageDialog(null, "Help:\n\n" +
"How to play-\n" +
"Select an empty square. The square will be filled with"
+ "with your symbole, either X or O.\n" +
"The game is won when either player gets three X's or"
+ "O's in a row horizontally,\n vertically, or diagonally.");
}
if (button.getText() == "" && player1)
{
button.setText("X");
turnCount += 1;
player1 = false;
player2 = true;
}
else if (button.getText() == "" && player2)
{
button.setText("O");
turnCount+=1;
player2 = false;
player1 = true;
}
else if (button.getText() == "X" || button.getText() == "O")
{
if(player2 == true)
{
gamePlay();
}
else
{
JOptionPane.showMessageDialog(null, "Invalid choice. Select"
+ " another square.");
}
}
}
}
}
Check this TicTacToe Full code using the Applets...:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
<applet code="TicTacToe.class" width="300" height="300">
</applet>
*/
public class TicTacToe extends Applet implements ActionListener {
Button[] btnarray = new Button[9];
private final static String PLAYER1 = "PLAYER1";
private final static String PLAYER2 = "PLAYER2";
private static String CURRENT_PLAYER = null;
Label lbl = new Label();
public void init() {
CURRENT_PLAYER = PLAYER1;
lbl.setText(CURRENT_PLAYER + " Turn!");
setLayout(new BorderLayout());
Panel p = new Panel();
GridLayout gl = new GridLayout(3, 3);
p.setLayout(gl);
setBackground(Color.BLACK);
setForeground(Color.WHITE);
setSize(300, 300);
Font myFont = new Font("TimesRoman", Font.BOLD, 80);
for (int i = 0; i < 9; i++) {
btnarray[i] = new Button(null);
btnarray[i].setActionCommand("" + i);
btnarray[i].addActionListener(this);
btnarray[i].setFont(myFont);
btnarray[i].setBackground(Color.white);
p.add(btnarray[i]);
}
add(BorderLayout.CENTER, p);
add(BorderLayout.NORTH, lbl);
add(BorderLayout.SOUTH, new Label("Player 1 => X , Player 2 => 0"));
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int index = Integer.parseInt(e.getActionCommand());
btnarray[index].disable();
if (CURRENT_PLAYER == PLAYER1) {
btnarray[index].setLabel("X");
CURRENT_PLAYER = PLAYER2;
} else {
btnarray[index].setLabel("0");
CURRENT_PLAYER = PLAYER1;
}
lbl.setText(CURRENT_PLAYER + " Turn!");
check();
}
void check() {
String[] pattern = new String[8];
pattern[0] = btnarray[0].getLabel() + btnarray[1].getLabel()
+ btnarray[2].getLabel();
pattern[1] = btnarray[3].getLabel() + btnarray[4].getLabel()
+ btnarray[5].getLabel();
pattern[2] = btnarray[6].getLabel() + btnarray[7].getLabel()
+ btnarray[8].getLabel();
pattern[3] = btnarray[0].getLabel() + btnarray[3].getLabel()
+ btnarray[6].getLabel();
pattern[4] = btnarray[1].getLabel() + btnarray[4].getLabel()
+ btnarray[7].getLabel();
pattern[5] = btnarray[2].getLabel() + btnarray[5].getLabel()
+ btnarray[8].getLabel();
pattern[6] = btnarray[0].getLabel() + btnarray[4].getLabel()
+ btnarray[8].getLabel();
pattern[7] = btnarray[2].getLabel() + btnarray[4].getLabel()
+ btnarray[6].getLabel();
int j = 0;
while (j < 8) {
char[] array = pattern[j].toCharArray();
if (array[0] == 'X' && array[1] == 'X' && array[2] == 'X') {
lbl.setText(PLAYER1 + " Wins!");
} else if (array[0] == '0' && array[1] == '0' && array[2] == '0') {
lbl.setText(PLAYER2 + " Wins!");
}
j++;
}
}
}
Related
My score in my JAVA coin toss program is multiplied instead of incremented and i have no idea why it's happening. I also know that i have some redundant code in this thing (ex. buttonsPanel.add(button2);
buttonsPanel.add(button); this.add(buttonsPanel); titlePanel.add(titleText); this.add(titlePanel); this.add(player_turn); this.add(playerOneScore); this.add(playerTwoScore); I will solve it after i find the solution to my score problem. )
Here is my code :
`
Random random = new Random();
int player1Score = 0;
int player2Score = 0;
JPanel buttonsPanel;
JButton button;
JButton button2;
JPanel titlePanel;
JLabel titleText;
JLabel player_turn;
JLabel playerOneScore;
JLabel playerTwoScore;
CoinToss(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Coin Toss test");
this.setSize(600,600);
this.setLayout(null);
this.getContentPane().setBackground(Color.black);
titlePanel = new JPanel();
titlePanel.setBackground(Color.blue);
titlePanel.setBounds(200, 10, 200, 40);
titleText = new JLabel();
titleText.setBackground(Color.blue);
titleText.setForeground(Color.yellow);
titleText.setFont(new Font("Ink Free",Font.ITALIC,25));
titleText.setHorizontalAlignment(JLabel.CENTER);
titleText.setText("Coin Toss Game");
titleText.setOpaque(true);
player_turn = new JLabel();
player_turn.setBounds(225, 200, 150, 50);
player_turn.setBackground(Color.blue);
player_turn.setForeground(Color.yellow);
player_turn.setFont(new Font("Ink Free",Font.ITALIC,25));
player_turn.setHorizontalAlignment(JLabel.CENTER);
player_turn.setText("Player1 turn");
player_turn.setOpaque(true);
buttonsPanel = new JPanel();
buttonsPanel.setBounds(200, 400, 200, 50);
buttonsPanel.setBackground(Color.blue);
button = new JButton("Tails");
button.setFocusable(false);
button.addActionListener(this);
button.setFont(new Font("Ink Free",Font.ITALIC,25));
button.setForeground(Color.green);
button2 = new JButton("Heads");
button2.addActionListener(this);
button2.setFocusable(false);
button2.setFont(new Font("Ink Free",Font.ITALIC,25));
button2.setForeground(Color.green);
playerOneScore = new JLabel();
playerOneScore.setBounds(50, 270, 210, 50);
playerOneScore.setBackground(Color.blue);
playerOneScore.setText("Player 1 score is : "+player1Score);
playerOneScore.setFont(new Font("Ink Free",Font.ITALIC,25));
playerOneScore.setOpaque(true);
playerTwoScore = new JLabel();
playerTwoScore.setBounds(350, 270, 210, 50);
playerTwoScore.setBackground(Color.blue);
playerTwoScore.setText("Player 2 score is : "+player2Score);
playerTwoScore.setFont(new Font("Ink Free",Font.ITALIC,25));
playerTwoScore.setOpaque(true);
buttonsPanel.add(button2);
buttonsPanel.add(button);
this.add(buttonsPanel);
titlePanel.add(titleText);
this.add(titlePanel);
this.add(player_turn);
this.add(playerOneScore);
this.add(playerTwoScore);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
int result = toss_coin(random);
if(e.getSource() == button2 ) {
if(result == 0) {
player1CorrectGuess();
updatePLayerTurn();
}
else {
player2IncorrectGuess(result);
updatePLayerTurn2();
}
}
else if(e.getSource() == button) {
if(result == 1) {
player1CorrectGuess();
updatePLayerTurn2();
}
else {
player2IncorrectGuess(result);
updatePLayerTurn();
}
}
WinRate();
}
static int toss_coin(Random random) {
int result = random.nextInt(2);
return result;
}
private void player1CorrectGuess() {
JOptionPane.showMessageDialog(null, "Correct. It's heads");
player1Score++;
playerOneScore.setText("Player 1 score is : "+player1Score);
}
private void player2IncorrectGuess(int result) {
JOptionPane.showMessageDialog(null, "Incorrect, the result was : " + (result == 0 ? "heads" : "tails") + ".");
player2Score++;
playerTwoScore.setText("Player 2 score is : "+player1Score);
}
private void updatePLayerTurn() {
player_turn.setText("Player2 turn");
}
private void updatePLayerTurn2() {
player_turn.setText("Player1 turn");
}
private void WinRate() {
int totalNumberOfSimulations = 20;
int numberOfWinsForPlayer1 = 0;
int numberOfWinsForPlayer2 = 0;
int maxScore = 10;
boolean turn_start = true;
for(int i=0;i<totalNumberOfSimulations;i++) {
player1Score = 0;
player2Score = 0;
while(player1Score < maxScore && player2Score < maxScore) {
int result = toss_coin(random);
if(turn_start) {
if(result == 0) {
player1Score++;
}
turn_start = false;
}
else {
if(result == 1) {
player2Score++;
}
turn_start = true;
}
if (player1Score == maxScore) {
numberOfWinsForPlayer1++;
}
else if(player2Score == maxScore) {
numberOfWinsForPlayer2++;
}
if (player1Score == maxScore && player2Score == maxScore) {
JOptionPane.showMessageDialog(null, "It's a tie, nobody wins.");
}
}
}
int winningChances = (numberOfWinsForPlayer1 * 100) / totalNumberOfSimulations;
int winningChances2 = (numberOfWinsForPlayer2 * 100) / totalNumberOfSimulations;
JOptionPane.showMessageDialog(null, "Player 1 winning chances: " + winningChances + "%"+"\nPlayer 2 winning chances: "+ winningChances2+ "%"); ;
//System.out.println("Player 1 winning chances: " + winningChances + "%");
//System.out.println("Player 2 winning chances: " + winningChances2 + "%");
}`
I tried getting help from chat GPT but that thing confused me even more.
I am currently making a Chess program as a project for my data structures class. We pretty much have most of the code complete but for some reason, I cannot figure out how to place the pieces onto any help would be Greatly Appreciated.
we are using JAVA and Swing
MAIN GOAL:
get piece IMG to go onto the board:
public abstract class UserInterface {
//FIELDS
protected Board board;
//The board that the UI will be used to interact with
//CONSTRUCTORS
public UserInterface(Board board) {
//Constructor for UserInterface implementers
this.board = board;
}
public UserInterface() {
}
//OTHER
public abstract Move promptMove();
public abstract PieceType promptPromotion();
public abstract void updateBoard();
public abstract void playGame(Interactable whiteUser, Interactable blackUser);
}
class CommandInterface extends UserInterface {
private GraphicInterface gui = null;
//CONSTRUCTORS
public CommandInterface(Board board) {
//Main constructor for the CommandInterface
super(board);
gui = new GraphicInterface(board, null);
gui.initializeGui();
}
//OTHER
public void playGame(Interactable whiteUser, Interactable blackUser) {
//Starts a game using the UI and the board.
//[TEST CODE] Probably will clean this up later
board.setUsers(whiteUser, blackUser);
updateBoard();
Scanner input = new Scanner(System.in);
boolean gameOver = false;
while(!gameOver) {
boolean illegalMove;
do {
try {
// System.out.println("Press enter to move");
// String s = input.nextLine();
board.doMove(board.getCurrentUser().getMove());
illegalMove = false;
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
illegalMove = true;
}
if(board.getState() == BoardState.CHECKMATE) {
System.out.println("\n" + board.getTurn().toString() + " is now checkmated. Game over!");
gameOver = true;
illegalMove = false;
} else if(board.getState() == BoardState.CHECK) {
System.out.println("\n" + board.getTurn().toString() + " has been put in check!");
illegalMove = false;
} else if(board.getState() == BoardState.STALEMATE) {
System.out.println("\n" + board.getTurn().toString() + " is now stalemated. Game over!");
gameOver = true;
illegalMove = false;
}
} while(illegalMove);
updateBoard();
}
}
public Move promptMove() {
//Takes user input for a move and returns the Move object
Scanner input = new Scanner(System.in);
String move;
boolean again;
do {
System.out.print("Enter your move (? for help): ");
move = input.nextLine();
if(move.equals("?")) {
//If the user asks for help
System.out.printf("%nHELP: To move, you must type a move in the following format:"
+ "%n<STARTING TILE> <ENDING TILE>"
+ "%nThe starting tile is the tile of the piece you wish to move."
+ "%nThe ending tile is the tile you wish to move your piece to."
+ "%nEach tile is notated with \"<COLUMN><RANK>\", example: \"e5\""
+ "%n%nFull example move: \"a5 g5\"%n");
again = true;
} else if(move.equalsIgnoreCase("CASTLE")) {
System.out.print("Enter the movement of the King: ");
move = input.nextLine();
return new Move(board, move, true);
} else again = false;
} while(again);
//Reprompt if the user asks for help
return new Move(board, move);
//Returns a Move object made from the SMN string
}
public PieceType promptPromotion() {
Scanner input = new Scanner(System.in);
System.out.print("Pawn has promotion available.\nWhich piece to promote to? ");
while(true) {
String type = input.nextLine();
PieceType promotion = PieceType.NONE;
if (type.equalsIgnoreCase("PAWN")) promotion = PieceType.PAWN;
else if (type.equalsIgnoreCase("ROOK")) promotion = PieceType.ROOK;
else if (type.equalsIgnoreCase("KNIGHT")) promotion = PieceType.KNIGHT;
else if (type.equalsIgnoreCase("BISHOP")) promotion = PieceType.BISHOP;
else if (type.equalsIgnoreCase("QUEEN")) promotion = PieceType.QUEEN;
else if (type.equalsIgnoreCase("KING")) promotion = PieceType.KING;
else if (type.equalsIgnoreCase("EARL")) promotion = PieceType.EARL;
else if (type.equalsIgnoreCase("MONK")) promotion = PieceType.MONK;
if(promotion == PieceType.NONE) {
System.out.print("\nInvalid type, please try again: ");
continue;
}
return promotion;
}
}
public void updateBoard() {
//Prints the board in basic ASCII format.
gui.updateBoard();
drawCaptured(Color.WHITE);
System.out.println();
//Adds a line before the board starts printing
int squaresPrinted = 0;
//Keeps track of the total number of squares that has been printed
for(int y = board.getZeroSize(); y >= 0; y--) {
//Loop through y-values from top to bottom
if(y != board.getZeroSize()) System.out.println();
//If not on the first iteration of y-loop, go down a line (avoids leading line break)
System.out.print((y + 1) + " ");
//Print the rank number
for(int x = 0; x <= board.getZeroSize(); x++) {
//Loop through x-values from left to right
if(board.pieceAt(x, y) != null) {
//If there is a piece on the tile
if(squaresPrinted % 2 == 0) System.out.print("[" + board.pieceAt(x, y).getString() + "]");
//If squaresPrinted is even, print "[<pString>]"
else System.out.print("(" + board.pieceAt(x, y).getString() + ")");
//If squaresPrinted is odd, print "(<pString>)"
} else {
//If there is no piece on the tile
if(squaresPrinted % 2 == 0) System.out.print("[ ]");
//If squaresPrinted is even, print "[ ]"
else System.out.print("( )");
//If squaresPrinted is odd, print "( )"
}
squaresPrinted++;
//Increment squaresPrinted for each iteration of the x-loop
}
squaresPrinted++;
//Increment squaresPrinted for each iteration of the y-loop
}
System.out.println();
System.out.print(" ");
//Print an extra line and the leading whitespace for the column identifiers
for(int i = 0; i <= board.getZeroSize(); i++) {
//Repeat <size> times
System.out.print(" " + (char) (i + 97));
//Print the column identifier chars by casting from int
}
drawCaptured(Color.BLACK);
//Prints all black pieces that have been captured
System.out.println();
}
private void drawCaptured(Color color) {
//Prints captured pieces of either color.
System.out.println();
//Prints a blank line
ArrayList<String> capturedPieces = board.getCaptured(color);
if(capturedPieces == null) return;
for(String p : capturedPieces) {
System.out.print(p + " ");
//TODO: Remove trailing whitespace
}
}
}
#SuppressWarnings("ALL")
class GraphicInterface extends UserInterface implements MouseListener {
private JButton[][] chessBoardSquares = null;
private JButton buttonsAndLabels = new JButton();
private JLabel message = null;
private String columnNames = null;
private Board board = null;
private JFrame frame;
public ImageIcon BK;
public ImageIcon WP;
public ImageIcon WR;
public ImageIcon WN;
public ImageIcon WB;
public ImageIcon WQ;
public ImageIcon WK;
public ImageIcon BP;
public ImageIcon BR;
public ImageIcon BN;
public ImageIcon BB;
public ImageIcon BQ;
public ImageIcon blank;
private Object ImageIcon;
public GraphicInterface(Board board, GraphicInterface frame) {
super(board);
// super(board);
this.board = board;
try {
//remove later
String path = "src/chuss/icons/";
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BK.gif")));
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WP.gif")));
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WR.gif")));
WN = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WN.gif")));
WB = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WB.gif")));
WQ = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WQ.gif")));
WK = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WK.gif")));
BP = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BP.gif")));
BR = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BR.gif")));
BN = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BN.gif")));
BB = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BB.gif")));
BQ = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BQ.gif")));
blank = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "blank.png")));
buttonsAndLabels.addMouseListener((MouseListener) this);
buttonsAndLabels.add(buttonsAndLabels);
buttonsAndLabels.setSize(600, 600);
//buttonsAndLabels.getContentPane().setPreferredSize(new Dimension(800, 700));
} catch(IOException e) {
e.getCause();
e.printStackTrace();
}
buttonsAndLabels = new JButton((Action) new BorderLayout(3, 3));
chessBoardSquares = new JButton[8][8];
message = new JLabel("Chuss Champ is ready to play!");
columnNames = "ABCDEFGH";
initializeGui();
}
public GraphicInterface(JButton buttonsAndLabels) {
super();
}
public GraphicInterface(Board board) {
}
#Override
public Move promptMove() {
return null;
}
#Override
public PieceType promptPromotion() {
return null;
}
public final JButton initializeGui() {
// set up the main GUI
assert false;
buttonsAndLabels.setBorder(new EmptyBorder(5, 5, 5, 5));
JToolBar tools = new JToolBar();
tools.setFloatable(false);
buttonsAndLabels.add(tools, BorderLayout.PAGE_START);
tools.add(new JButton("New")); // TODO - add functionality!
tools.add(new JButton("Save")); // TODO - add functionality!
tools.add(new JButton("Restore")); // TODO - add functionality!
tools.addSeparator();
tools.add(new JButton("Resign")); // TODO - add functionality!
tools.addSeparator();
tools.add(message);
buttonsAndLabels.add(new JLabel("?"), BorderLayout.LINE_START);
// create the chess board squares
buttonsAndLabels = new JButton((Action) new GridLayout(0, 9));
buttonsAndLabels.setBorder(new LineBorder(java.awt.Color.BLACK));
buttonsAndLabels.add((Component) ImageIcon);
updateBoard();
Runnable r = () -> {
JFrame f = new JFrame("CHUSS");
f.add(getGui());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// ensures the minimum size is enforced.
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
assert false;
return null;
}
public void updateBoard() {
//Prints the board in graphical format.
buttonsAndLabels.removeAll();
Insets buttonMargin = new Insets(0,0,0,0);
for (int ii = 7; ii >= 0; ii--) {
for (int jj = 0; jj < chessBoardSquares.length; jj++) {
JButton b = new JButton();
b.setMargin(buttonMargin);
// our chess pieces are 64x64 px in size, so we'll
// 'fill this in' using a transparent icon..
Piece p = board.pieceAt(jj, ii);
ImageIcon icon = new ImageIcon();
if (p instanceof Pawn && p.getColor() == Color.WHITE) icon = WP;
else if (p instanceof Rook && p.getColor() == Color.WHITE) icon = WR;
else if (p instanceof Knight && p.getColor() == Color.WHITE) icon = WN;
else if (p instanceof Bishop && p.getColor() == Color.WHITE) icon = WB;
else if (p instanceof Queen && p.getColor() == Color.WHITE) icon = WQ;
else if (p instanceof King && p.getColor() == Color.WHITE) icon = WK;
else if (p instanceof Pawn && p.getColor() == Color.BLACK) icon = BP;
else if (p instanceof Rook && p.getColor() == Color.BLACK) icon = BR;
else if (p instanceof Knight && p.getColor() == Color.BLACK) icon = BN;
else if (p instanceof Bishop && p.getColor() == Color.BLACK) icon = BB;
else if (p instanceof Queen && p.getColor() == Color.BLACK) icon = BQ;
else if (p instanceof King && p.getColor() == Color.BLACK) icon = BK;
else if (p == null) icon = blank;
b.setIcon(icon);
if ((jj % 2 == 1 && ii % 2 == 1)
//) {
|| (jj % 2 == 0 && ii % 2 == 0)) {
b.setBackground(java.awt.Color.WHITE);
} else {
b.setBackground(java.awt.Color.GRAY);
}
chessBoardSquares[jj][ii] = b;
buttonsAndLabels.add(chessBoardSquares[jj][ii]);
}
}
initializeGui();
// fill the top row
for (int ii = 0; ii <= 7; ii++) {
buttonsAndLabels.add(
new JLabel(columnNames.substring(ii, ii + 1),
SwingConstants.CENTER));
}
// fill the black non-pawn piece row
for (int ii = 7; ii >= 0; ii--) {
for (int jj = 0; jj < 8; jj++) {
if (jj == 0) {
buttonsAndLabels.add(new JLabel("" + (ii + 1),
SwingConstants.CENTER));
}
buttonsAndLabels.add(chessBoardSquares[jj][ii]);
}
}
buttonsAndLabels.updateUI();
}
#Override
public void playGame(Interactable whiteUser, Interactable blackUser) {
GraphicInterface gui = new GraphicInterface(buttonsAndLabels);
gui.getChessBoard();
}
public JComponent getChessBoard() {
return buttonsAndLabels;
}
public JComponent getGui() {
return buttonsAndLabels;
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
I am working on building the game of Tic Tac Toe. Please find below the description of the classes used.
Game:: The main class. This class will initiate the multiplayer mode.
Board: This class sets the board configurations.
Computer: This class comprises of the minimax algorithm.
BoardState: This class comprises of the Board Object, along with the last x and y coordinates which were used to generate the board
configuration.
State: This class comprises of the score and the x and y coordinates that that will lead to that score in the game.
Context
Working on DFS here.
Exploring the whole tree works fine.
The game is set in such a way that the user is prompted to play first.
The user will put x and y co ordinates in the game.Coordinates are between 0 to 2. The Play of the player is marked as 1
The response from the computer is 2, which the algorithm decides. Th algorithm will determine the best possible coordinates to play and then play 2 on the position.
One of the winning configurations for Player is :
Player wins through diagonal
121
112
221
One of the winning configuration for AI is:
222
121
211
AI wins Horizontal
Problem
All the states give the max score.
Essentially, when you start the game in your system, you will find that since all states are given the max score, the computer looks to play sequentially.
As in if you put at (00), the computer plays at (01) and if you play at (02), the computer will play at (10)
I have been trying to debug it for a long time now. I believe, I may be messing up something with the scoring function. Or there could be a bug in the base recursion steps. Moreover, I don't think immutability among classes could cause problems as I have been recreating/creating new objects everywhere.
I understand, this might not be the best context I could give, but it would be a great help if you guys could help me figure out where exactly is it going wrong and what could I do to fix it. Answers through code/logic used would be highly appreciated. Thanks!
Game Class
import java.io.Console;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Game {
static int player1 = 1;
static int player2 = 2;
public static void main(String[] args) {
// TODO Auto-generated method stub
//
//PLays Game
playGame();
/* Test Use Case
ArrayList<Board> ar = new ArrayList<Board>();
Board b = new Board();
b.setVal(0,0,1);
b.setVal(0,1,1);
b.setVal(0,2,2);
b.setVal(1,0,2);
b.setVal(1,1,2);
b.setVal(2,0,1);
b.setVal(2,1,1);
b.display();
Computer comp = new Computer();
State x = comp.getMoves(b, 2);
*/
}
private static void playGame() {
// TODO Auto-generated method stub
Board b = new Board();
Computer comp = new Computer();
while(true)
{
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
int[] pmove = getPlayerMove(b);
b.setVal(pmove[0],pmove[1], player1);
if(b.isVictoriousConfig(player1))
{
System.out.println("Player 1 Wins");
break;
}
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
System.out.println("Computer Moves");
/*For Random Play
* int[] cmove = comp.computeMove(b);
*/
Computer compu = new Computer();
State s = compu.getMoves(b, 2);
int[] cmove = new int[2];
cmove[0] = s.x;
cmove[1] = s.y;
b.setVal(cmove[0],cmove[1], player2);
if(b.isVictoriousConfig(player2))
{
System.out.println("Computer Wins");
break;
}
}
System.out.println("Game Over");
}
//Gets Player Move. Basic Checks on whether the move is a valud move or not.
private static int[] getPlayerMove(Board b) {
// TODO Auto-generated method stub
int[] playerMove = new int[2];
System.out.println("You Play");
while(true)
{
#SuppressWarnings("resource")
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter X Position: ");
while(true)
{
playerMove[0] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[0] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("Enter Y Position: ");
while(true)
{
playerMove[1] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[1] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("You entered positions: X is " + playerMove[0] + " and Y is " + playerMove[1] );
if(!b.isPosOccupied(playerMove[0], playerMove[1]))
{
break;
}
System.out.println("Incorrect Move. PLease try again");
}
return playerMove;
}
}
Board Class
import java.util.Arrays;
public class Board {
// Defines Board Configuration
private final int[][] data ;
public Board()
{
data = new int[3][3];
for(int i=0;i<data.length;i++ )
{
for(int j=0;j<data.length;j++ )
{
data[i][j] = 0;
}
}
}
//Displays Current State of the board
public void display()
{
System.out.println("Board");
for(int i = 0; i< data.length;i++)
{
for(int j = 0; j< data.length;j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
// Gets the Value on a specific board configuration
public int getVal(int i, int j)
{
return data[i][j];
}
//Sets the value to a particular board location
public void setVal(int i, int j,int val)
{
data[i][j] = val;
}
public boolean isBoardFull()
{
for(int i=0;i< data.length ; i++)
{
for(int j=0;j< data.length ;j++)
{
if(data[i][j] == 0)
return false;
}
}
return true;
}
public boolean isVictoriousConfig(int player)
{
//Noting down victory rules
//Horizontal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [0][1]) && (data[0][1] == data [0][2]) && (data[0][2] == player)))
return true;
if ((data[1][0] != 0) && ((data[1][0] == data [1][1]) && (data[1][1] == data [1][2]) && (data[1][2] == player)))
return true;
if ((data[2][0] != 0) && ((data[2][0] == data [2][1]) && (data[2][1] == data [2][2]) && (data[2][2] == player)))
return true;
//Vertical Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][0]) && (data[1][0] == data [2][0]) && (data[2][0] == player)))
return true;
if ((data[0][1] != 0) && ((data[0][1] == data [1][1]) && (data[1][1] == data [2][1]) && (data[2][1] == player)))
return true;
if ((data[0][2] != 0) && ((data[0][2] == data [1][2]) && (data[1][2] == data [2][2]) && (data[2][2] == player)))
return true;
//Diagonal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][1]) && (data[1][1] == data [2][2]) && (data[2][2] == player)))
return true;
if ( (data[0][2] != 0) && ((data[0][2] == data [1][1]) && (data[1][1] == data [2][0]) && (data[2][0] == player)))
return true;
//If none of the victory rules are met. No one has won just yet ;)
return false;
}
public boolean isPosOccupied(int i, int j)
{
if(data[i][j] != 0)
{
return true;
}
return false;
}
public Board(int[][] x)
{
this.data = Arrays.copyOf(x, x.length);
}
}
Board State
public class BoardState {
final Board br;
final int x ;
final int y;
public BoardState(Board b, int posX, int posY)
{
br = b;
x = posX;
y = posY;
}
}
State
public class State {
final int s;
final int x;
final int y;
public State(int score, int posX, int posY)
{
s = score;
x = posX;
y = posY;
}
}
Computer
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class Computer {
int[] pos = new int[2];
static int player2 = 2;
static int player1 = 1;
ArrayList<Board> win =new ArrayList<Board>();
ArrayList<Board> loose =new ArrayList<Board>();
ArrayList<Board> draw =new ArrayList<Board>();
public Computer()
{
}
public int[] computeMove(Board b)
{
while(true)
{
Random randX = new Random();
Random randY = new Random();
pos[0] = randX.nextInt(3);
pos[1] = randY.nextInt(3);
if(!b.isPosOccupied(pos[0], pos[1]))
{
return pos;
}
}
}
public State getMoves(Board b,int p)
{
//System.out.println("test2");
int x = 0;
int y = 0;
BoardState bs = new BoardState(b,0,0);
//System.out.println("test");
State s = computeMoveAI(bs,p);
//System.out.println("Sore : X : Y" + s.s + s.x + s.y);
return s;
}
private State computeMoveAI(BoardState b, int p) {
// TODO Auto-generated method stub
//System.out.println("Hello");
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.br.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("d is ");
//d.display();
//System.out.println("p is "+ p);
int xvalue= b.x;
int yvalue = b.y;
BoardState bs = new BoardState(d,xvalue,yvalue);
if(getConfigScore(d,p) == 1)
{
//System.out.println("Winning Config");
//System.out.println("X is " + b.x + " Y is " + b.y);
// b.br.display();
State s = new State(-1,bs.x,bs.y);
return s;
}
else if (getConfigScore(d,p) == -1)
{
//System.out.println("LooseConfig");
State s = new State(1,bs.x,bs.y);
//System.out.println("Coordinates are "+bs.x + bs.y+ " for " + p);
return s;
}
else if(bs.br.isBoardFull())
{
//System.out.println("Board is full");
State s = new State(0,bs.x,bs.y);
//System.out.println("score " + s.s + "x "+ s.x + "y "+ s.y);
return s;
}
else
{
//Get Turn
//System.out.println("In else condiyion");
int turn;
if(p == 2)
{
turn = 1;
}else
{
turn = 2;
}
ArrayList<BoardState> brr = new ArrayList<BoardState>();
ArrayList<State> st = new ArrayList<State>();
brr = getAllStates(d,p);
for(int k=0;k<brr.size();k++)
{
//System.out.println("Goes in " + "turn " + turn);
//brr.get(k).br.display();
int xxxxx = computeMoveAI(brr.get(k),turn).s;
State temp = new State(xxxxx,brr.get(k).x,brr.get(k).y);
st.add(temp);
}
//Find all Nodes.
//Go to First Node and proceed with recursion.
//System.out.println("Displaying boards");
for(int i=0;i<brr.size();i++)
{
//brr.get(i).br.display();
//System.out.println(brr.get(i).x + " " + brr.get(i).y);
}
//System.out.println("Board configs are");
for(int i=0;i<st.size();i++)
{
//System.out.println(st.get(i).x + " " + st.get(i).y + " and score " + st.get(i).s);
}
//System.out.println("xvalue" + xvalue);
//System.out.println("yvalue" + yvalue);
//System.out.println("Board was");
//d.display();
//System.out.println("Coming to scores");
//System.out.println(" p is "+ p);
if(p == 2)
{
//System.out.println("Size of first response" + st.size());
//System.out.println("Returns Max");
return max(st);
}
else
{
//System.out.println("The last");
return min(st);
}
}
}
private State min(ArrayList<State> st) {
// TODO Auto-generated method stub
ArrayList<State> st1= new ArrayList<State>();
st1= st;
int min = st.get(0).s;
//System.out.println("Min score is " + min);
for(int i=1;i<st1.size();i++)
{
if(min > st1.get(i).s)
{
min = st1.get(i).s;
//System.out.println("Min is");
//System.out.println(min);
//System.out.println("Min" + min);
State s = new State(min,st1.get(i).x,st1.get(i).y);
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Exits Min");
//System.out.println("Min Score" + st1.get(0).s + " x" + st1.get(0).x + "y " + st1.get(0).y);
return s;
}
private State max(ArrayList<State> st) {
// TODO Auto-generated method stub
//System.out.println("Size of first response in funciton is " + st.size());
ArrayList<State> st1= new ArrayList<State>();
st1 = st;
int max = st1.get(0).s;
for(int i=0;i<st1.size();i++)
{
// System.out.println(i+1 + " config is: " + "X:" + st1.get(i).x + "Y:" + st1.get(i).y + " with score " + st1.get(i).s);
}
for(int i=1;i<st1.size();i++)
{
//.out.println("Next Item " + i + st.get(i).s + "Coordinates X"+ st.get(i).x +"Coordinates Y"+ st.get(i).y );
if(max < st1.get(i).s)
{
max = st1.get(i).s;
//System.out.println("Max" + max);
//System.out.println("Max is");
//System.out.println(max);
State s = new State(max,st1.get(i).x,st1.get(i).y);
//System.out.println("Max Score returned" + s.s);
//System.out.println("Returned");
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Max is outer");
//System.out.println(st.get(0).s);
return s;
}
//Basic brain Behind Min Max algorithm
public int getConfigScore(Board b,int p)
{
int score;
int turn ;
int opponent;
if(p == player1)
{
turn = p;
opponent = player2;
}
else
{
turn = player2;
opponent = player1;
}
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("s arrasy is ");
//d.display();
//System.out.println("turn is " + turn);
if(d.isVictoriousConfig(turn))
{
score = 1;
}
else if(d.isVictoriousConfig(opponent))
{
score = -1;
}
else
{
score = 0;
}
return score;
}
public static ArrayList<BoardState> getAllStates(Board b, int player)
{
ArrayList<BoardState> arr = new ArrayList<BoardState>();
int[][]s1 = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s1[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(s1);
for(int i = 0;i <3; i ++)
{
for (int j=0;j<3;j++)
{
if(!d.isPosOccupied(i, j))
{
int previousState = d.getVal(i, j);
int[][]s = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s[i1][j1] = d.getVal(i1, j1);
}
}
s[i][j] = player;
Board d1 = new Board(s);
BoardState bs = new BoardState(d1,i,j);
arr.add(bs);
}
}
}
return arr;
}
}
This is the output of the test case in the Game class:
Board
1 1 2
2 2 0
1 1 0
Score : X : Y -> 1: 1: 2
The solution here is score:1 for x:1, y:2. It looks correct.
But again, you could say since it is moving sequentially, and since position (1,2) will come before (2,2), it gets the right coordinate.
I understand that this may be huge lines of code to figure out the problem. But
computemoveAI(), getConfigScore() could be the functions to look out for. Also I do not want to bias your thoughts with where I think the problem could as sometimes, we look somewhere , but the problem lies elsewhere.!!
I don't understand the int a; in the main that I called st in the Action listener. I want the st to decrease for 1 everytime a cetain button is clicked but it seems to work separetly for each button. I made it so it writes it out on a button each time I press another button to test it and it only works for the first button and then it just stays the same. (I hope I'm making any sense)
Here is my code, Main class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Start {
public static int a;
public static JButton[][] gumbi = new JButton[15][15];
public static void main(String[] args) {
JFrame okno = new JFrame("Nonogram");
okno.setVisible(true);
okno.setSize(700, 700);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
okno.add(panel);
JPanel polje = new JPanel(new GridLayout(15, 15));
panel.add(polje, BorderLayout.CENTER);
a = 0;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (i < 5 && j < 5) {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.GREEN);
// gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
} else if (i < 5 || j < 5) {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.YELLOW);
// gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
gumbi[i][j].setEnabled(false);
} else {
if (Math.random() <= 0.6) {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("3");
polje.add(gumbi[i][j]);
} else {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("4");
polje.add(gumbi[i][j]);
}
}
if (gumbi[i][j].getText() == "3") {
a += 1;
}
if (i == 14 && j == 14) {
gumbi[i][j].setText("" + a);
}
}
}
}
}
and ActionListener:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Listener implements ActionListener {
JButton[][] gumbi = Start.gumbi;
int st = Start.a;
public Listener(JButton[][] gumbi) {
this.gumbi = gumbi;
}
public void actionPerformed(ActionEvent e){
JButton gumb = (JButton) e.getSource();
if( gumb.getBackground() == Color.WHITE){
gumb.setBackground(Color.BLACK);
} else if (gumb.getBackground() == Color.BLACK){
gumb.setBackground(Color.WHITE);
}
if( gumb.getBackground() == Color.WHITE && gumb.getText() == "3"){
st -= 1;
} else if (gumb.getBackground() == Color.BLACK && gumb.getText() == "3"){
st += 1;
gumbi[0][0].setText("" + st);
}
}
}
The problem is that you created a copy of the Static Variable(Start.a) to the instance variable (st), which will be individual copy for each instance of action listener.
If you really need to maintain the value at class level , why not manipulate the value directly rather keeping a copy.
if( gumb.getBackground() == Color.WHITE && gumb.getText() == "3"){
Start.a -= 1;
} else if (gumb.getBackground() == Color.BLACK && gumb.getText() == "3"){
Start.a += 1;
gumbi[0][0].setText("" + st);
}
Your line
int st = Start.a;
isn't doing what you think. It's reading the value of a when the instance is created, and copying its value into a new variable st. Changing st won't have any effect on a because you're only changing a copy; and you've got a new copy for each instance that you create.
Try changing Start.a directly, rather than copying it into a new st and changing that.
I'm creating a GUI calculator, using FlowLayout, GridLayout and BorderLayout. I have the following code.
import java.awt.*;
import javax.swing.*;
//Imports visual components for program
import java.awt.event.*;
//Imports functions for providing performing action on object
public class Calc extends JFrame implements ActionListener {
JPanel[] row = new JPanel[5];
//5 panels are created for 5 rows of buttons
JButton[] button = new JButton[19];
String[] buttonString = {"1","2","3","+","4","5","6","-",
"7","8","9","*",".","/","C","rt","%",
"=", "0"};
double[] temporary = {0,0};
//Two memory locations for current number and upcoming number for signs such as *,/,%,+,-
boolean[] sign = new boolean[5];
//5 values for +,-,*,/,% are stored in array because they expect another number upon invocation
JTextArea display = new JTextArea(1,10);
//Creates display with location specified
Calc(){
//Constructor begins here
setResizable(false);
//Sets calculator size to be fixed at 380x250
//5x5 is created and selected for the calculator
for(int a = 0; a < 5; a++)
sign[a] = false;
//Initialises the state of the signs for +,-,*,/,%
JPanel displaypanel = new JPanel();
JPanel first = new JPanel();
JPanel last = new JPanel();
//Create three panels for buttons to be placed in
displaypanel.setLayout(new FlowLayout());
displaypanel.add(display);
//Display is added
first.setLayout(new GridLayout(3,5));
for(int a = 0; a<15; a++)
first.add(button[a]);
//"first" panel is added
last.setLayout(new GridLayout(1,4));
last.add(button[15]);
last.add(button[16]);
last.add(button[17]);
last.add(button[18]);
JFrame window = new JFrame("Task twelve");
window.setLayout(new BorderLayout());
window.add(displaypanel, BorderLayout.PAGE_START);
window.add(first, BorderLayout.CENTER);
window.add(last, BorderLayout.PAGE_END);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 400);
for(int a = 0; a < 19; a++){
button[a] = new JButton();
button[a].setText(buttonString[a]);
button[a].addActionListener(this);
//Assigns all the numbers and signs for the buttons
}
for(int a = 0; a < 5; a++)
row[a] = new JPanel();
//Initialises JPanel for rows so they can be used
//Assigns size for all buttons and display
display.setEditable(false);
}
public void clear(){
try{
display.setText("");
//Sets the display to be blank
for(int a = 0; a < 5; a++)
sign[a] = false;
//Sets state of all signs to be false
temporary[0] = 0;
temporary[1] = 0;
//Sets temporary values to be 0 as well
} catch(NullPointerException e){
}
}
public void root(){
try{
double temp = Math.sqrt(Double.parseDouble(display.getText()));
//Creates variable that converts the value in display to a double and Sqroots the value
display.setText(Double.toString(temp));
//Converts value in temp to string and copies it to display
} catch(NullPointerException e){
}
}
public void getResult() {
double result = 0;
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp2 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp2[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp3 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp3[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
if(sign[0] == true)
//Addition sign
result = temporary[0] + temporary[1];
else if(sign[1] == true)
//Subtraction sign
result = temporary[0] - temporary[1];
else if(sign[2] == true)
//Multiplication sign
result = temporary[0] * temporary[1];
else if(sign[3] == true)
//Division sign
result = temporary[0] / temporary[1];
else if(sign[4] == true)
//Modulus sign
result = temporary[0] % temporary[1];
display.setText(Double.toString(result));
for(int a = 0; a < 5; a++)
sign[a] = false;
//Sets state of all signs to be false after one of them has been invoked
} catch(NumberFormatException e) {
}
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == button[0])
display.append("1");
//When "1" is pressed, "1" is inserted to the display
if(ae.getSource() == button[1])
display.append("2");
if(ae.getSource() == button[2])
display.append("3");
if(ae.getSource() == button[3]){
//Addition sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[0] = true;
display.setText("");
}
if(ae.getSource() == button[4])
display.append("4");
if(ae.getSource() == button[5])
display.append("5");
if(ae.getSource() == button[6])
display.append("6");
if(ae.getSource() == button[7]){
//Subtraction sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("7");
if(ae.getSource() == button[9])
display.append("8");
if(ae.getSource() == button[10])
display.append("9");
if(ae.getSource() == button[11]){
//Multiplication sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append(".");
if(ae.getSource() == button[13]){
//Division sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[3] = true;
display.setText("");
}
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15])
root();
if(ae.getSource() == button[16]){
//Modulus sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[4] = true;
display.setText("");
}
if(ae.getSource() == button[17])
getResult();
if(ae.getSource() == button[18])
display.append("0");
}
public static void main(String[] args){
Calc c = new Calc();
}
}
Compiling this doesn't result in any errors. However, running the class does.
Exception in thread"main" java.lang.NullPointerException
at java.awt.Container.addlmpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Calc.<init>(Calc.java:43)
at Calc.main(Calc.java:198)
I don't understand these errors so I do not know how to fix this. Can anyone help?
You are creating 15 buttons in the loop button[a] = new JButton(buttonString[a]); but then you are asking for button[15, 16, ...] (the 16nth, 17nth... button you have not created) and are null.