Could someone please look over this code and make sure there are no errors in it? I've looked through it again and again and I can't see what's wrong. However when I run the program (a Rock Paper scissors game) it seems that the second constructor isn't called correctly or something, because it doesn't output any text as it should, and it has a text field and button that don't need to be there. I'm somewhat confused on why it does this.

guiExecution class: (this is the one I could use some help with the other class is included so you can compile it if you wish.)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class guiExecution extends JFrame implements ActionListener
{
        private static String results;
	private static int playerNum = 40;			//max num of players
	private static int count;					// count for current player
	private static int initClick;				// used for initial button click
	private static Player players[] = new Player[playerNum];	//create default players
	private static JLabel question = new JLabel("How many players to play?");
	private static JButton submit = new JButton("Submit");
	private static JTextField userData = new JTextField(20);
        private static guiExecution window = new guiExecution();         // original question gui
		
	public guiExecution()
	{// default constructor for original gui frame for question entry
		// called by main method
		
		/* add action listener to submit button*/
            submit.addActionListener(this);
		 /* create a container, determine a layout*/
            Container c = getContentPane();
            c.setLayout(new FlowLayout());
		 /* add labels, button and textfield*/
            c.add(question);
            c.add(userData);
            c.add(submit);
            userData.setEditable(true);		
	}

	public guiExecution(String results)
	{ // second constructor for showing the results of the game
		// called after all players are created and all challenges are made

		/* create a container*/
            Container c = getContentPane();
		 /* create a text area that has the results String within it*/
            question.setText(results);
		 /* add the text area to the container*/
            c.add(question);
	}


	public void actionPerformed(ActionEvent e)
	{// this method is executed each time submit button is clicked
            String playerName;
		if (initClick == 0)	// the first time its clicked is to submit the number of players
		{
			playerNum = Integer.parseInt(userData.getText()); // set playerNum field
			initClick++;			// make sure initClick not equal 0 any longer
			userData.setText("");	// clear input field of gui
			question.setText("What is the name of player " + (count + 1) + "? ");	// change question label text
		}
		else // all other clicks are for player name entries
		{
			/* create each player with string from userData (count is your index)*/
                    playerName = userData.getText();
                    players[count] = new Player(playerName);
			/* increase player count */
                    count++;
			/* clear input field of gui */
                    userData.setText("");
			/* if not total number of players desired create yet, ask for next player */
                    if(count < playerNum)
                    {
                        question.setText("What is the name of player " + (count + 1) + "? ");
                    }
		}

		if (count == playerNum )// if all players have been created
		{ 
		/* play the game and retrieve game results and 
		 * winner counts and put within one string */
                    results = playGame(players);
                    results += showWinners(players);
                    window.hide();		// hide question frame
		/* create new gui frame that passes the string as a constructor argument */
                    new guiExecution(results);
		/* show the new frame */
                    window.show();
		}
	}

	public static void main (String args[])
	{	
		// window is the gui frame that is defined as a field
		window.setSize(400,200);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.show();
	}

	public static String playGame(Player players[])
	{
		// does not change from GameExecution class of chapter 16
            String gameResults = "";
		int j, k;

		/* use two for loops nested to make each player challenge the other players
		 * only once! HINT: outer loop goes through all players. Inner loop goes from
		 * last player to current outer loop player*/
                
                for (j = 0; j < playerNum; j++) 
                {
                    for (k = (playerNum - 1); k > j; k--)
                    {
                        if(j == k)
                        {
                            continue;
                        }
                            players[j].challenge(players[k]);   // challenge player[j] with player[k]
                            /* Save current player's results to gameResults total.
                            * Put each player result on a new line.
                            */
                            gameResults += players[j].getWins() + "\n";
                    }
            }
		/* return game results string */
                return gameResults;
	}

	public static String showWinners(Player players[])
	{
		// does not change from GameExecution class of chapter 16
            String allWinners = "";
		/* loop through all the players and save to the allWinners string
		 * how many times each player won. Put each player on a new line.
		 */
                for(int i = 0; i < playerNum; i++)
                {
                    int playerWins = players[i].returnWins();
                    allWinners = allWinners + players[i].getName() + " won " + playerWins + " times.\n"; 
                }
		
		/* return allWinners string */
                return allWinners;
	}

}

Player class:

public class Player
{
	private String PlayerName;				// Player's Identifying Name 
	private String State;					// Player's Rock/Paper/Scissors State
	private int stateValue;					// State Value for switch statement
	private String output;					// Result string of current game winner
	private int wins;						// number of wins for this player

	public Player(String n)
	{	// constructor that sets PlayerName identifier and State of Player with P,R or S
		PlayerName = n;	
		stateValue = n.length()%3;	// determine state on length of name
		switch (stateValue)
		{
			case 0: State = "Paper"; break;
			case 1: State = "Rock"; break;
			case 2: State = "Scissors"; break;
			default: State = "Rock"; 
		}
	}

	/* create method that returns the players name*/
        public String getName()
        {
            return PlayerName;
        }
	

	public String returnState()		// method that returns player's current state
	{
        changeState();	// change state before returning
		return State;	// return state string value
	}

	/* create method that adds 1 to win total */
        public void addWins()
        {
            wins += 1;
        }

	/* create method that returns win total */
        public int returnWins()
        {
            return wins;
        }

	/* create method that returns the current winner output*/
        public String getWins()
        {
            return output;
        }

	public void changeState()
	{
            stateValue = PlayerName.length() % 3;
            stateValue += 1;
            if(stateValue > 2)
            {
                stateValue = 0;
            }
            
            switch(stateValue)
            {
                case 0: State = "Paper"; break;
                case 1: State = "Rock"; break;
                case 2: State = "Scissors"; break;
                default: State = "Rock"; break;
            }
		/* add code that increases the state value and then changes the 
		 * Player's State accordingly. Look at the constructor for help and be sure
		 * the state value never goes above 2!*/
	}

	public void challenge(Player p2)	// called when game is played
	{
		String p2State = p2.returnState();  // get the value of the other player's State

		if (State.equals(p2State)) changeState();  // change current player state if same as p2

		if (State.equals("Paper") && p2State.equals("Rock"))
		{
			/* set the output string field to display which player won over
			 * which other player and what their states were to win*/
                    output = getName() + " defeats " + p2.getName() + " with paper over rock.";

			/* call the method of the winner to add a win to their win total */
                    addWins();
		}
                else if(State.equals("Paper") && p2State.equals("Scissors"))
                {
                    output = p2.getName() + " defeats " + getName() + " with scissors over paper"; 
                    p2.addWins();
                }
		else if (State.equals("Rock")&& p2State.equals("Scissors"))/*compare and find results repeating for all 6 game possibilities*/
		{
                    output = getName() + " defeats " + p2.getName() + " with rock over scissors.";
                    addWins();
                }
                else if(State.equals("Rock") && p2State.equals("Paper"))
                {
                    output = p2.getName() + " defeats " + getName() + " with paper over rock";
                    p2.addWins();
                }
                else if(State.equals("Scissors") && p2State.equals("Paper"))
                {// need comparisons for paper to scissors, rock to paper, scissors to paper, etc
                    output = getName() + " defeats " + p2.getName() + " with Scissors over paper.";
                    addWins();
                }
                else if(State.equals("Scissors") && p2State.equals("Rock"))
                {
                    output = p2.getName() + " defeats " + getName() + " with rock over scissors.";
                    p2.addWins();
                }
                
	}
}

Recommended Answers

All 7 Replies

You should stick with java naming conventions. Don't start instance variable with capital letters, as that typically shows a Class name. And I have no clue what this is suppose to do:

stateValue = PlayerName.length() % 3;

if playerName = "Bobby" then statValue would equal 2 (5 mod 3)

So the player doesn't pick their choice? It's based on the length of their name?

yes, that is correct, the choice made based on the players name, I thought that was a little odd too, but it is a requirement.

I figured out the problem, in the guiExecution class I had

new guiExecution(results);

and I needed

window = new guiExecution(results);

man do I feel stupid right about now :o thanks for the naming suggestion thing though.

I'm glad this thread is still up, and hopefully someone will look at it again. I guess I have this program basically done, in fact it seems to work just fine on my computer, however when I sent this assignment in to be graded I was told that when 4 players are entered in it only challenges three against each other, and that it does thes three incorrectly. As I said it seems to work fine on my computer, the only thing that I've noticed is that there is an extra string in the output that simply states "null" when I run the program on my computer it challenges all the players entered in against each other.

if you want to compile, or just look at the code, I updated the actionPerformed(ActionEvent e) to this:

public void actionPerformed(ActionEvent e)
	{// this method is executed each time submit button is clicked
            //String playerName;
		if (initClick == 0)	// the first time its clicked is to submit the number of players
		{
			playerNum = Integer.parseInt(userData.getText()); // set playerNum field
			initClick++;			// make sure initClick not equal 0 any longer
			userData.setText("");	// clear input field of gui
			question.setText("What is the name of player " + (count + 1) + "? ");	// change question label text
		}
		else // all other clicks are for player name entries
		{
			/* create each player with string from userData (count is your index)*/
                    playerName = userData.getText();
                    players[count] = new Player(playerName);
			/* increase player count */
                    count++;
			/* clear input field of gui */
                    userData.setText("");
			/* if not total number of players desired create yet, ask for next player */
                    if(count < playerNum)
                    {
                        question.setText("What is the name of player " + (count + 1) + "? ");
                    }
		}

		if (count == playerNum )// if all players have been created
		{ 
		/* play the game and retrieve game results and 
		 * winner counts and put within one string */
                    results = playGame(players);
                    results += showWinners(players);
                    window.hide();		// hide question frame
		/* create new gui frame that passes the string as a constructor argument */
                    window = new guiExecution(results);
                    window.setSize(400, 400);
                    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		/* show the new frame */
                    window.show();
		}
	}

otherwise the two classes remain the same. Thanks for any help :)

does anybody have a simple program for player play with comp. and use import Keyboard and Random only?

does anybody have a simple program for player play with comp. and use import Keyboard and Random only?

You should make a new thread if you have a question, and this is not even a comprehensible question. You'll want to restate it if you do make a thread.

does anybody have a simple program for player play with comp. and use import Keyboard and Random only?

the answer to this is propably 'yes', but who that anybody is... I have no clue. figure out what you want out of your program, figure out the logics behind it, start programming and show us the code if you are stuck with any bugs.

BUT...

do NOT
+ pollute other threads with questions that have nothing to do with the subject
+ expect us to deliver custom made code
+ expect us to be willing to help you if you don't even try to make it look like you've made an effort

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.