I am trying to output the information from the Salaried class in the EmployeesApplet class using the toString method in Salaried, however i keep receiving the error
EmployeesApplet.java:292: error: non-static method toString() cannot be referenced from a static context
ta.append(Salaried.toString());
^
How do i get around this error to display the information correctly?
here is the Salaried class
public class Salaried extends Employee
{
private double weekly_salary;
public Salaried(String first_name, String last_name, int e, double w ) // one constructor
{
super(first_name,last_name, e);
weekly_salary = w;
}
public String toString()
{
return super.toString() + " \nWeekly Salary" + weekly_salary ;
} // toString method
}
and here is the EmployeesApplet class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EmployeesApplet extends JApplet implements ActionListener
{
public JButton sd = new JButton ("Salaried");
public JButton hr = new JButton ("Hourly");
public JButton cm = new JButton ("Commissioned");
public JButton cl = new JButton ("Clear");
private final int FIELDS = 8,
FIELD_WIDTH = 20;
private String[] strings = new String[FIELDS];
private TextFieldWithLabel[] tf = new TextFieldWithLabel[FIELDS];
private JTextArea ta = new JTextArea(5,25);
String[] s = {"First Name", "Last Name", "Employee ID", "(a) Salaried: Weekly Salary", "(b1) Hourly 1: Rate Per Hour",
"(b2) Hourly 2: Hours Worked" , "(c1) Commissioned: Rate", "(c2) Commissioned: Gross Sales" };
public void init()
{
this.setSize(420, 310);
//----------------------
// Set up the Structure
//----------------------
Container c = getContentPane();
JPanel f = new JPanel(new FlowLayout());
JPanel b = new JPanel(new BorderLayout(2,0));
JPanel glb = new JPanel(new GridLayout(8,1,0,2));
JPanel gtf = new JPanel(new GridLayout(8,1,0,2));
JPanel flb = new JPanel(new FlowLayout());
// Add FlowLayout to the container
c.add(f);
// Add BorderLayout to the FlowLayout
f.add(b);
//---------------------------------------
//Add JPanels to the BorderLayout regions
//---------------------------------------
// Add JLables to GridLayout in West
b.add(glb, BorderLayout.WEST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
glb.add(tf[i].getLabel());
}
// Add JTextFeilds to GridLayout in East
b.add(gtf, BorderLayout.EAST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
tf[i].getTextField();
gtf.add(tf[i].getTextField());
}
// Add JButtons to FlowLayout in South
b.add(flb, BorderLayout.SOUTH);
flb.add(sd);
flb.add(hr);
flb.add(cm);
flb.add(cl);
sd.addActionListener(this);
hr.addActionListener(this);
cm.addActionListener(this);
cl.addActionListener(this);
// Add JTextArea and make it not editable
f.add(ta);
ta.setEditable(false);
}
//---------------------------------------
// Read all the JTextFields and
// save the contents in a parallel array
//---------------------------------------
private void readFields()
{
for (int i = 0; i < tf.length; i++) // or FIELDS
strings[i] = tf[i].getText();
}
private boolean fieldsExist(int i, int i2)
{
if(i == 0 && i2 == 3) // Checks Salaried worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty"); // Diplays error message in status area
tf[0].getTextField().requestFocus(); // Places focus in JTextField
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else if(tf[3].getText() == null || tf[3].getText().length() == 0)
{
showStatus("(a)Salried: Weekly Salary field is empty");
tf[3].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 0 && i2 == 2) // Checks Hourly worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 4 && i2 == 5) // Checks Hourly worker the second time
{
if(tf[4].getText() == null || tf[4].getText().length() == 0)
{
showStatus("(b1) Hourly 1: Rate Per Hour field is empty");
tf[5].getTextField().requestFocus();
return false;
}
else if(tf[5].getText() == null || tf[5].getText().length() == 0)
{
showStatus("(b2) Hourly 2: Hours Worked field is empty");
tf[5].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 0 && i2 == 2) // Checks Commissioned worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 6 && i2 == 7) // Checks Commissioned second time
{
if(tf[6].getText() == null || tf[6].getText().length() == 0)
{
showStatus("(c1)Commissioned: Rate field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[7].getText() == null || tf[7].getText().length() == 0)
{
showStatus("(c2)Commissioned: Ratefield is empty");
tf[1].getTextField().requestFocus();
return false;
}
else
return true;
}
return false;
}
private boolean fieldsEmpty(int i, int i2, String[] a)
{
if(i == 4 && i2 == 7) // checks salaried
{
for (int index = 4; index <= 7; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus( a[index] + " should be empty"); // Diplays error message in status area
tf[index].getTextField().requestFocus(); // Places focus in JTextField
return true;
}
else return false;
} // end for
} // end if
if (i == 3 && i2 == 3) // checks hourly first time
{
if(tf[3].getText().length() != 0)
{
showStatus(a[3] + " field should be empty");
tf[3].getTextField().requestFocus();
return true;
}
} // end if
if(i == 6 && i2 == 7) // checks hourly second time
{
for (int index = 6; index <= 7; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus(a[index] + " field should be empty");
tf[index].getTextField().requestFocus();
return true;
}
} // end for
} // end if
if(i == 3 && i2 == 5) // checks commissioned
{
for (int index = 3; index <= 5; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus(a[index] + " field should be empty");
tf[index].getTextField().requestFocus();
return true;
}
} // end for
} // end if
return false;
}
public void actionPerformed(ActionEvent e)
{
showStatus("");
if (e.getSource() == cl) // Executes clear button is clicked
{
for (int i = 0; i < FIELDS; i++)
{
tf[i].getTextField().setText("");
tf[0].getTextField().requestFocus();
}
} // End clear if
if (e.getSource() != cl)
{
if(e.getSource() == sd) // checks for salaried employee
{
showStatus("Salaried");
fieldsExist(0,3);
fieldsEmpty(4,7, s);
ta.append(Salaried.toString());
} // end salaried
if(e.getSource() == hr) // checks for hourly employee
{
showStatus("Hourly");
fieldsExist(0,2);
fieldsExist(4,5);
fieldsEmpty(3,3, s);
fieldsEmpty(6,7, s);
} // end hourly
if(e.getSource() == cm) // checks for commissioned employee
{
showStatus("Commissioned");
fieldsExist(0,2);
fieldsExist(6,7);
fieldsEmpty(3,5, s);
} // end commisssioned
} // end if
} // End of actionPerformed
}
As the error states, toString() is not static, you need to run it on an instance of Salaried. e.g.
Salaried s = new Salaried();
s.toString(); // should work...
Without relevant section from EmployeeApplet I cannot advise further, note ta.append(Salaried.toString()); in the error message you posted, does not appear to correspond to fragment of EmployeeApplet you gave...
Related
i have a class in a java program where i am using a toString function to retrieve data. the toString checks a private function in the same class which returns a int value, for displaying different types of return messages.~
The problem is that if i use a local variable in the string function every turns out good, but if i check in the if statements directlly the private function, this function doesnt return any value.
private int computerTryHorizontalPlay() {
int repeatedMyValueCount = 0;
int repeatedYourValueCount = 0;
int[] myPositions = new int[3];
int[] yourPositions = new int[3];
for (int a = 0; a < 3; a++) {
int repeatedMyValue = 0;
int repeatedYourValue = 0;
int emptyFields = 0;
int[] emptyPosition = new int[2];
for (int b = 0; b < 3; b++) {
if (jogoGalo[a][b] == 'X') {
repeatedMyValue++;
} else if (jogoGalo[a][b] == 'O') {
repeatedYourValue++;
}
if (jogoGalo[a][b] == '-') {
emptyPosition[0] = a;
emptyPosition[1] = b;
emptyFields++;
}
}
if (repeatedMyValue == 3 || repeatedYourValue == 3) {
return 3;
} else {
if (emptyFields == 1) {
if (repeatedMyValue == 2) {
repeatedMyValueCount++;
myPositions[repeatedMyValueCount - 1] = emptyPosition[0];
myPositions[repeatedMyValueCount] = emptyPosition[1];
} else if (repeatedYourValue == 2) {
repeatedYourValueCount++;
yourPositions[repeatedYourValueCount - 1] = emptyPosition[0];
yourPositions[repeatedYourValueCount] = emptyPosition[1];
}
}
}
}
if (repeatedMyValueCount > 0) {
jogoGalo[myPositions[0]][myPositions[1]] = 'X';
return 2;
} else if (repeatedYourValueCount > 0) {
jogoGalo[yourPositions[0]][yourPositions[1]] = 'X';
return 1;
}
return 0;
}
This doesn´t work!
public String toString() {
if(computerTryHorizontalPlay() == 3) {
return "The game has already ended!";
}
else if(computerTryHorizontalPlay() == 2) {
return "Computer won!";
}
else if(computerTryHorizontalPlay() == 1) {
return "Computer defendeu!";
}
return null;
}
This works!
public String toString() {
int horizontalFunctionValue = computerTryHorizontalPlay();
if(horizontalFunctionValue == 3) {
return "The game has already ended!";
}
else if(horizontalFunctionValue == 2) {
return "Computer won!";
}
else if(horizontalFunctionValue == 1) {
return "Computer defendeu!";
}
return null;
}
}
toString() must be a read-only method, i.e. it is not allowed to have side-effects like changing the state of the object. Since computerTryHorizontalPlay() is a state-changing method, you are not allowed to call it from toString().
Since the only state-change happens in the last if statement, you can change the code to not execute the play when called from toString(), like this:
private int computerTryHorizontalPlay() {
return computerTryHorizontalPlay(true);
}
private int computerTryHorizontalPlay(boolean doMove) {
// lots of code here
if (repeatedMyValueCount > 0) {
if (doMove)
jogoGalo[myPositions[0]][myPositions[1]] = 'X';
return 2;
} else if (repeatedYourValueCount > 0) {
if (doMove)
jogoGalo[yourPositions[0]][yourPositions[1]] = 'X';
return 1;
}
return 0;
}
public String toString() {
if(computerTryHorizontalPlay(false) == 3) {
return "The game has already ended!";
}
else if(computerTryHorizontalPlay(false) == 2) {
return "Computer won!";
}
else if(computerTryHorizontalPlay(false) == 1) {
return "Computer defeated!";
}
return null;
}
I have written Tic-Tac-Toe in Java. The issue I seem to be having is when there is a tie between the (human)player 1 and the (computer) player 2, the GUI freezes. I have created a tieCheck in both the "Buttonlistener" Class and the "Methods" to catch a tie.
The way my program works is that when a button is pressed, it passes a value to the array in the methods class. in this array, 1 = player 1, and 2 = player 2.
The human player always goes first, so when the human player has gone 4 times, I check for a tie before the last turn is taken with tieCheck(turncount); this method then utilizes the tieCheck() in the methods class which will place a 1 in the last place and then checks for a winner. if no winner is found, it returns true. then the tieCheck() from the ButtonListener class will disable all the buttons, and say "it is a tie". However, none of this is working. The program will still allow me to make the last move and will result in a frozen window I have to close using task manager. please help!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MediumPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JButton playAgain;
private JButton[] buttons = new JButton[9];
private JLabel label, turn;
public MediumPanel() {
ButtonListener listener = new ButtonListener();
Font f1 = new Font("Arial", Font.BOLD , 100);
Font f2 = new Font("Arial", Font.PLAIN, 50);
JPanel ButtonPanel = new JPanel();
ButtonPanel.setLayout(new GridLayout(3, 3));
for (int i = 0; i <= 8; i++) {
buttons[i] = new JButton("");
buttons[i].addActionListener(listener);
buttons[i].setBackground(Color.white);
buttons[i].setFont(f1);
ButtonPanel.add(buttons[i]);
}
playAgain = new JButton();
label = new JLabel();
label.setFont(f2);
turn = new JLabel("");
turn.setFont(f1);
playAgain.addActionListener(listener);
playAgain.setText("Click to Play Again");
playAgain.setFont(f2);
setBackground(Color.green);
setLayout(new BorderLayout());
setPreferredSize(new Dimension(500, 500));
add(playAgain, BorderLayout.SOUTH);
add(label, BorderLayout.NORTH);
add(ButtonPanel);
}
private class ButtonListener implements ActionListener {
Methods method = new Methods();
public void reset() {
label.setText("");
for (int i = 0; i <= 8; i++) {
buttons[i].setEnabled(true);
buttons[i].setText("");
}
method.reset();
}
// inserts
public void insertG(int num) {
for (int i = 0; i <= 8; i++) {
if (num == i) {
buttons[i].setText("O");
buttons[i].setEnabled(false);
}
}
}
public void disable() {
for(int i=0; i<=8; i++) {
buttons[i].setEnabled(false);
}
}
// Checks array using tieCheck from Methods class for a tie
public void tieCheck(int turncount) {
if (turncount == 4 && method.tieCheck() == true) {
disable();
label.setText("It's a tie!");
}
}
// Checks for buttons being pressed
public void actionPerformed(ActionEvent event) {
int turncount = 0;
//Resets array board, GUI buttons, and label when clicked
if (event.getSource() == playAgain) {
reset();
}
// Button 0
if (event.getSource() == buttons[0]) {
buttons[0].setText("X");
buttons[0].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(0, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 1
if (event.getSource() == buttons[1]) {
buttons[1].setText("X");
buttons[1].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(1, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 2
if (event.getSource() == buttons[2]) {
buttons[2].setText("X");
buttons[2].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(2, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 3
if (event.getSource() == buttons[3]) {
buttons[3].setText("X");
buttons[3].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(3, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 4
if (event.getSource() == buttons[4]) {
buttons[4].setText("X");
buttons[4].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(4, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 5
if (event.getSource() == buttons[5]) {
buttons[5].setText("X");
buttons[5].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(5, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
//Button 6
if (event.getSource() == buttons[6]) {
buttons[6].setText("X");
buttons[6].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(6, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 7
if (event.getSource() == buttons[7]) {
buttons[7].setText("X");
buttons[7].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(7, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
//Button 8
if (event.getSource() == buttons[8]) {
buttons[8].setText("X");
buttons[8].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(8, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
}
}
}
import java.util.*;
public class Methods {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
// represents Tick-Tack-Toe Play Field
int[] board = new int[9];
// resets board array
public void reset() {
for (int i = 0; i < 9; i++) {
board[i] = 0;
}
}
// inserts player on a specific spot
public void insertArray(int spot, int player) {
board[spot] = player;
}
// for hard mode
public void expertMove(int player1, int player2) {
}
// for medium
public int smartMove(int player1, int player2) {
boolean turntaken = false;
for (int i = 0; i < 9; i++) {
if (board[i] == 0) {
board[i] = player2;
if (winCheck(player2) == 1) {
return i;
} else {
board[i] = 0;
}
}
}
for (int i = 0; i < 9; i++) {
if (board[i] == 0) {
board[i] = player1;
if (winCheck(player1) != 1) {
board[i] = 0;
} else {
board[i] = player2;
return i;
}
}
}
// If the opposite player is not about to win, then Computer goes randomly
if (turntaken == false) {
return randomMove(player2);
}
return 0;
}
// For easy mode and also utilized in smartMove() for medium mode
public int randomMove(int player) {
int rnum = 0;
rnum = rand.nextInt(8);
while (emptyCheck(rnum) != true) {
rnum = rand.nextInt(8);
}
board[rnum] = player;
return rnum;
}
//Returns 1 if player won the game
public int winCheck(int player) {
for (int ii = 0; ii <= 2; ii++) {
if (board[ii] == player && board[ii + 3] == player && board[ii + 6] == player)
return 1;
}
for (int z = 0; z <= 6; z = z + 3) {
if (board[z] == player && board[z + 1] == player && board[z + 2] == player)
return 1;
}
if (board[0] == player && board[4] == player && board[8] == player) {
return 1;
}
if (board[2] == player && board[4] == player && board[6] == player) {
return 1;
}
return 0;
}
//Returns true if tie
public boolean tieCheck() {
for(int i=0;i < 9; i++) {
if(board[i] == 0) {
board[i] = 2;
if(winCheck(1) != 1 && winCheck(2) != 1) {
return true;
}else {
board[i] = 0;
}
}
}
return false;
}
// Checks if empty: True if empty/false if taken by player
public boolean emptyCheck(int rnum) {
if (board[rnum] == 0) {
return true;
} else {
return false;
}
}
}
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class Driver {
public static void main(String []args) {
JTabbedPane difficulty = new JTabbedPane();
//difficulty.addTab("Easy", new EasyPanel());
difficulty.addTab("Medium", new MediumPanel());
//difficulty.addTab("Hard", new HardPanel());
Font f = new Font("Arial", Font.PLAIN, 20);
difficulty.setFont(f);
JFrame frame = new JFrame("Tic-Tac-Toe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(difficulty);
frame.pack();
frame.setVisible(true);
}
On every click, you set turncount = 0:
// Checks for buttons being pressed
public void actionPerformed(ActionEvent event) {
int turncount = 0;
but in your method tieCheck:
// Checks array using tieCheck from Methods class for a tie
public void tieCheck(int turncount) {
if (turncount == 4 && method.tieCheck() == true) {
disable();
label.setText("It's a tie!");
}
}
you check if turncount == 4but it is always 1. You should change the turncount variable from local to global.
And then in method randomMove, you have an endless loop:
// For easy mode and also utilized in smartMove() for medium mode
public int randomMove(int player) {
int rnum = 0;
rnum = rand.nextInt(8);
while (emptyCheck(rnum) != true) { // <--------- HERE
rnum = rand.nextInt(8);
}
Like Peter1982 said in his answer, you should make turncount a class variable instead of a method variable so that it doesn't get reset every time you call the actionPerformed method.
To stop the game from getting frozen, you can create a boolean class variable that keeps track of if the game is over, such as gameOver. You then update gameOver in the tieCheck method, for example:
private class ButtonListener implements ActionListener {
boolean gameOver = false;
// ...
// Checks array using tieCheck from Methods class for a tie
public void tieCheck(int turncount) {
if (turncount == 4 && method.tieCheck() == true) {
gameOver = true; // <---- Update gameOver
disable();
label.setText("It's a tie!");
}
}
// Button 0
if (event.getSource() == buttons[0]) {
buttons[0].setText("X");
buttons[0].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(0, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else if (!gameOver) { // <---- Check if the game is over
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// ...
}
Make sure to reset turncount and tieCheck in your reset method.
Also, as an extra note, when I was looking through your code, I noticed that in your randomMove method you have the following: rnum = rand.nextInt(8);. Currently, this won't allow the computer to make a random move on the 9th button because rand.nextInt(8) will return a value of 0 through 7. This is because the 8 is exclusive. So just put 9 as the parameter like this: rand.nextInt(9) to get 0 through 8. I know it is trivial but I just wanted to point it out.
I am an AP Computer Science student and I need help with my assignment for the class. My assignment is to create a simple GUI or game using Eclipse. I made a simple player vs. player tic-tac-toe game, but I do not know how to create a "reset" button for my GUI. I tried multiple times, but I can't get it to work or show up in my GUI. I would appreciate some pointers on how to implement a functional reset button, so I would not have exit out of my GUI multiple times to start playing again. Here is the code I have written so far.
package gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToeGUI implements ActionListener
{
JFrame window = new JFrame("Tic-Tac-Toe");
JButton[] button;
JButton reset = new JButton("Reset");
String letter = "";
public int count = 0;
public boolean win = false;
public TicTacToeGUI()
{
button = new JButton[9];
window.setSize(300,300);
window.setLayout(new GridLayout(3,3));
JButton dummy = new JButton("");
Font font = dummy.getFont();
Font bigFont = font.deriveFont(font.getSize2D() * 5.0f);
JButton reset = new JButton("Reset");
for(int i = 0; i < 9; i++)
{
button[i] = new JButton("");
button[i].setFont(bigFont);
button[i].addActionListener(this);
window.add(button[i]);
}
window.setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
count++;
if(count % 2 == 1)
{
letter = "X";
}
else
{
letter = "O";
}
Object but = a.getSource();
for(int i = 0; i < 9; i++)
{
if(but == button[i])
{
button[i].setText(letter);
button[i].setEnabled(false);
break;
}
}
if( button[0].getText() == button[1].getText() && button[1].getText() == button[2].getText() && button[0].getText() != "")
{
win = true;
}
else if(button[3].getText() == button[4].getText() && button[4].getText() == button[5].getText() && button[3].getText() != "")
{
win = true;
}
else if(button[6].getText() == button[7].getText() && button[7].getText() == button[8].getText() && button[6].getText() != "")
{
win = true;
}
else if(button[0].getText() == button[3].getText() && button[3].getText() == button[6].getText() && button[0].getText() != "")
{
win = true;
}
else if(button[1].getText() == button[4].getText() && button[4].getText() == button[7].getText() && button[1].getText() != "")
{
win = true;
}
else if(button[2].getText() == button[5].getText() && button[5].getText() == button[8].getText() && button[2].getText() != "")
{
win = true;
}
else if(button[0].getText() == button[4].getText() && button[4].getText() == button[8].getText() && button[0].getText() != "")
{
win = true;
}
else if(button[2].getText() == button[4].getText() && button[4].getText() == button[6].getText() && button[2].getText() != "")
{
win = true;
}
else
{
win = false;
}
if(win == true)
{
JOptionPane.showMessageDialog(null, letter + " WINS!");
}
else if(count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "Tie Game!");
}
}
public static void main(String[] args)
{
new TicTacToeGUI();
}
}
You might want to try this:
window.setLayout(new BorderLayout());
JPanel panel = new JPanel( new GridLayout(3, 3));
window.add(panel, BorderLayout.CENTER); // add panel to window center
window.add(reset, BorderLayout.SOUTH); // add reset button to window bottom
Of course, you will have to add your 9 buttons to panel now, not to window.
But why don't you just reset automatically after the user confirmed the dialog at the end of the game?
Reset your board after a tie or win. An example reset method. Otherwise you are going to have to make room on your Frame to hold a button to do this.
private void ResetBoard() {
for(int i = 0; i < 9; i++) {
button[i].setText("");
button[i].setEnabled(true);
count = 0;
}
}
Then use this method when a check is made to see if a player won or the game ends in a tie as below:
if(win == true)
{
JOptionPane.showMessageDialog(null, letter + " WINS!");
ResetBoard();
}
else if(count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "Tie Game!");
ResetBoard();
}
I have to create the yahtzee game and its methods like full house, small straight, big straight, 3 of kind, 4 of kind , and chance. Now this is what i have done so far and i would like to know if my methods are right and also i'm having a hard time trying to figure out how to check if its yahtzee , 3 of kind, 4 of kind , etc and this is in my main method. The program consists of seven rolls, where every roll can have up to two sub-rolls
static final int NUM_RERROLS_ = 2;
static final int NUM_OF_DICE = 5;
static final int NUM_ROLLS_ = 7;
static final int[] dice = new int[NUM_OF_DICE];
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
rollDice();
for (int i = 0; i < NUM_RERROLS_; i++) {
if (gotYatzee()) {
break;
}
System.out.println(diceToString());
askUser();
System.out.println("Which dice do you want to reroll: ");
secondReroll(convert(keyboard.nextLine()));
}
System.out.println(diceToString());
if (gotYatzee()) {
System.out.println("You got Yatzee & 50 points!");
} else if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
{
System.out.println("SORRY NO YAHTZEE");
}
if (askUser() == false) {
if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
}
}
public static void rollDice() {
for (int i = 0; i < NUM_OF_DICE; i++) {
dice[i] = randomValue();
}
}
public static int randomValue() {
return (int) (Math.random() * 6 + 1);
}
public static String diceToString() {
String dado = "Here are your dice: ";
for (int element : dice) {
dado = dado + element + " ";
}
return dado;
}
public static boolean gotYatzee() {
for (int element : dice) {
if (element != dice[0]) {
return false;
}
}
return true;
}
public static void secondReroll(int[] newValue) {
for (int element : newValue) {
dice[element - 1] = randomValue();
}
}
public static int[] convert(String s) {
StringTokenizer st = new StringTokenizer(s);
int[] a = new int[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
a[i++] = Integer.parseInt(st.nextToken());
}
return a;
}
public static boolean Chance() {
for (int element : dice) {
int i = 0;
if (element != dice[i]) {
i++;
return false;
}
}
return true;
}
public static boolean smallStraight() {
for (int i = 1; i <= NUM_OF_DICE; i++) {
boolean b = false;
for (int j = 0; j < NUM_OF_DICE; j++) {
b = b || (dice[j] == i);
}
if (!b) {
return false;
}
}
return true;
}
public static boolean largeStraight() {
int[] i = new int[5];
i = dice;
sortArray(i);
if (((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5))
|| ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6))
|| ((i[1] == 1) && (i[2] == 2) && (i[3] == 3) && (i[4] == 4) && (i[5] == 5))
|| ((i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5) && (i[5] == 6))) {
return true;
} else {
return false;
}
}
public static boolean askUser() {
Scanner keyboard = new Scanner(System.in);
int a = 0;
String yes = "Yes";
String no = "No";
System.out.println("Do you want to reroll the dice again: Yes or No? ");
String userInput;
userInput = keyboard.next();
if (userInput.equals(yes)) {
System.out.println("ALRIGHTY!!");
return true;
} else if (userInput.equals(no)) {
}
return false;
}
public static boolean threeKind() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) // Three of a Kind
|| ((a[1] == a[2]) && ((a[2] == a[3])
|| (((a[2] == a[3]) && (a[3] == a[4]))))))) {
return true;
} else {
return false;
}
}
/*public static boolean fourKind(int[] dice) {
}
*/
public static int[] sortArray(int[] numbers) {
int stop;
for (stop = 0; stop < numbers.length; stop++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
swap(numbers, i, i + 1);
}
}
}
return numbers;
}
public static void swap(int[] numbers, int pos1, int pos2) {
int temp = numbers[pos1];
numbers[pos1] = numbers[pos2];
numbers[pos2] = temp;
}
public static boolean fullHouse() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) && // Three of a Kind
(a[3] == a[4]) && // Two of a Kind
(a[2] != a[3]))
|| ((a[0] == a[1]) && // Two of a Kind
((a[2] == a[3]) && (a[3] == a[4])) && // Three of a Kind
(a[1] != a[2]))) {
return true;
} else {
return false;
}
}
}
basically i want to figure out a way to check if its full house, 3 of kind, 4 of kind , etc
You have 6 dice after three rolls. Sort the array of user-retained dice after the 3 rolls.
Yahtzee: ((die[0] == die[4]) || (die[1] == die[5]))
4 of a kind: ((die[0] == die[3]) || (die[1] == die[4] || (die[2] == die[5]))
Small straight, 3 tests (x = 3,4,5): ((die[x] - die[x-3]) == 3)
Large straight, 2 tests (x = 4,5): ((die[x] - die[x-4]) == 4)
etc.
Chance: Up to the user, right?
Unless I'm missing something (I'm a little rusty on Yatzee), this should be fairly straightforward.
I am a beginner at programming and I have been teaching myself as much as I can. I need help in a simpler way of checking for a victory instead of hard coding every possible combination.
I have no idea what to do.
here is my current code:
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class connectfour extends JFrame implements ActionListener
{
JLabel board[][] = new JLabel[8][7];
//JLabel board[] = new JLabel[64];
JButton action[] = new JButton[8];
JButton start;
JButton clear;
JFrame Frame = new JFrame();
ImageIcon red = new ImageIcon("red piece.jpeg");
ImageIcon black = new ImageIcon("blackpiece.jpeg");
boolean players = true;
//Integer[] numclick = new Integer[8];
int x;
int numclick1 = 7;
int numclick2 = 7;
int numclick3 = 7;
int numclick4 = 7;
int numclick5 = 7;
int numclick6 = 7;
int numclick7 = 7;
int numclick0 = 7;
public connectfour()
{
Frame.setSize(100,120);
Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Frame.setLayout(null);
Frame.setVisible(true);
start = new JButton("Start");
start.setBounds(0,0,100,100);
start.setVisible(true);
start.addActionListener(this);
Frame.add(start);
}
public void game()
{
for(int x = 0; x < 8 ; x++)
{
action[x] = new JButton();
action[x].setSize(100,40);
action[x].setLocation((x*100) + 50, 0);
action[x].addActionListener(this);
action[x].setVisible(true);
Frame.add(action[x]);
}
/**
board[1][1] = new JLabel();
board[1][1].setBounds(50,40,100,100);
board[1][1].setVisible(true);
board[1][1].setOpaque(true);
board[1][1].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[1][1]);
**/
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 7; j++)
{
board[i][j] = new JLabel();
board[i][j].setSize(100,100);
board[i][j].setLocation((i*100)+50,(j*100)+40);
board[i][j].setOpaque(true);
board[i][j].setVisible(true);
board[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[i][j]);
}
}
clear = new JButton("Clear");
clear.setBounds(850,100,100,50);
clear.addActionListener(this);
clear.setVisible(true);
Frame.add(clear);
}
public void boardsize()
{
Frame.setSize(950,800);
}
public static void main(String args[])
{
new connectfour();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == start)
{
boardsize();
start.setVisible(false);
game();
}
for(x = 0;x < 8 ;x ++)
{
if(e.getSource() == action[x])
{
//numclick[x]++;
if(x == 0)
{
numclick0--;
if(players == true)
{
board[x][numclick0].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick0].setIcon(black);
players = true;
break;
}
}
if(x == 1)
{
numclick1--;
if(players == true)
{
board[x][numclick1].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick1].setIcon(black);
players = true;
break;
}
}
if(x == 2)
{
numclick2--;
if(players == true)
{
board[x][numclick2].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick2].setIcon(black);
players = true;
break;
}
}
if(x == 3)
{
numclick3--;
if(players == true)
{
board[x][numclick3].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick3].setIcon(black);
players = true;
break;
}
}
if(x == 4)
{
numclick4--;
if(players == true)
{
board[x][numclick4].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick4].setIcon(black);
players = true;
break;
}
}
if(x == 5)
{
numclick5--;
if(players == true)
{
board[x][numclick5].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick5].setIcon(black);
players = true;
break;
}
}
if(x == 6)
{
numclick6--;
if(players == true)
{
board[x][numclick6].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick6].setIcon(black);
players = true;
break;
}
}
if(x == 7)
{
numclick7--;
if(players == true)
{
board[x][numclick7].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick7].setIcon(black);
players = true;
break;
}
}
System.out.println(x);
System.out.println();
}
}
if(e.getSource() == clear)
{
for(int x = 0; x < 8; x++)
{
for(int y = 0; y < 7; y++)
{
board[x][y].setIcon(null);
numclick1 = 7;
numclick2 = 7;
numclick3 = 7;
numclick4 = 7;
numclick5 = 7;
numclick6 = 7;
numclick7 = 7;
numclick0 = 7;
players = true;
for(int j = 0; j < 8 ; j++)
{
action[j].setEnabled(true);
}
}
}
}
if(numclick0 == 0)
{
action[0].setEnabled(false);
}
if(numclick1 == 0)
{
action[1].setEnabled(false);
}
if(numclick2 == 0)
{
action[2].setEnabled(false);
}
if(numclick3 == 0)
{
action[3].setEnabled(false);
}
if(numclick4 == 0)
{
action[4].setEnabled(false);
}
if(numclick5 == 0)
{
action[5].setEnabled(false);
}
if(numclick6 == 0)
{
action[6].setEnabled(false);
}
if(numclick7 == 0)
{
action[7].setEnabled(false);
}
}
public void winner()
{
}
}
I would use a recursive method that checks the horizontal, vertical, and both diagonals.
As i was reading your code I realized you don't keep track(may have missed it) of where players are.. I recommend and array for this called grid[][] Mapping an array to your JLabels will go a long way.
Ill give an example of negative vertical check..
public Boolean checkVertical(Boolean player, int x, int y){
if(solveHelper(player, x, y, -1, 0) => 4) return true;
return false;
}
public int solveHelper(Boolean player, int x, int y, int addX, int addY){
if(x == 0 || x == size || y == 0 || y == size || grid[x][y].player != player)
return 0;
return solverHelper(player, x+addX, y+addY, addX, addY) + 1);
}
Now how can you create and use these methods for yourself?
you need to create a new methods for each of the horizontal, vertical, and both diagonals to check for all of them you call solveHelper with different properties in addX and addY that correspond with the direction you want to go. For instance, if you want to check the horizontal you need do make addY == 1 and addY == -1 with both values for addX == 0 by doing a solveHelper + solverHelper with these two values changed.
Other notes...
Some things you need to need to keep in mind is that how connect four actually runs. When you click on a row a piece falls down to the smallest unoccupied element in that particular column. Just something you should keep in mind when writing your game logic.
Cheers.