Running a class a particular number of times

hey

can some pls tell me how to run this class a specific number of times. maybe by using a for loop?.

i am making a game called memory game where u match the cards which are thw same. i want to make this a multiplayer game rather than a single player game. Thus in order to do this i need to be able to run the class (shown below) a specific number of times.

i have an array called "players" which is a length of 5. and if the user enter the names into all five elements or there are 5 players then i need the program to run 5 times. else if the user only entered a name in two elements then i need the class "MemoryMatch" to run twice .

i know how to determine whether the user entered 5 names or a single by using if statements. but i dont kno how to make the class "MemoryGame" run a specific number of times.

.. .and for the game i calculate the score of the user by finding the amount of time it takes the user to finish the game and then subtract the time they took from a base value of 500points. i then put the time difference into an array called "timez" i also want the class to add the time to array "timez" at the end after the one of the players has finished the game or the class is run.

here is the code for the "MemoryMatch" class which i need to run a specific number of times.

class MyButtonextends JButton

{

long startTime = System.currentTimeMillis ();

int index;

ImageIcon icon;

public MyButton (ImageIcon img,int i)

{

icon = img;

index = i;

setPreferredSize (new Dimension (100, 100));

addActionListener (new ActionListener ()

{

publicvoid actionPerformed (ActionEvent actionEvent)

{

// 1

/* Create and add a prompt and then a text field */

if (getIcon () ==null)

{

setIcon (icon);

if (buttonShowingIndex > -1)

{

if (icon != button [buttonShowingIndex].getIcon ())

{

finalint bsi = buttonShowingIndex;

ActionListener al =new ActionListener ()

{

publicvoid actionPerformed (ActionEvent actionEvent)

{

MyButton.this.setIcon (null);

button [bsi].setIcon (null);

}

}

;

javax.swing.Timer timer =new javax.swing.Timer (450, al);

timer.setRepeats (false);

timer.start ();

}

buttonShowingIndex = -1;

}

else

buttonShowingIndex = index;

//time calculation

long endTime = System.currentTimeMillis ();

long difference = ((endTime - startTime) / 1000) + 2;

timez [0] = difference;

}

}

}

);

}

}

so ...basically the two things i would like to get are

1. make the class "MemoryMatch" run a specific number of times

2. Put the time difference(time it takes user to finish game) into the array "timez" (but i think i got that handled but still if u knew a more efficient way... that would be nice =) )

thanks alot

[4460 byte] By [Nadal_Federera] at [2007-11-27 6:21:31]
# 1

You can always use the For Each loop construct to retrieve each element in a collection.

for (Player player : players) {

player.methodCall();

//do something

}

The variable players refers to your collection of Player objects. The variable player refers to that current instance of Player in that collection.

As far as figuring out time you can always use a System.getCurrentTimeMillis() for the start time and then at the end of your execution get the difference between the current time at that moment and the start time.

maple_shafta at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...
# 2
hey mancould u plz elaborate cuz this is my first yr doin java so i dont kno many things.could u plz put the For Each loop in the code i put earlier? thanks ..alot!
Nadal_Federera at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...
# 3

> hey man

> could u plz elaborate cuz this is my first yr doin

> java so i dont kno many things.

>

> could u plz put the For Each loop in the code i put

> earlier?

>

> thanks ..alot!

No time like the present to begin learning:

http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html

kevjavaa at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...
# 4

hey

i tried reading it but i could not get the program to work. everytime i get the error message"Misplaced constructs" ot "{ expected after token"

i added the For Each loop to the beginning of the class but it did not wrk. could u tell me wat its wrong with this? "players" is the name of the arrayof length 5 with the names of the people playing the game. where as the "MyButton" class is the class which is part of my game which checks to see of the user has clicked two same buttons.

i'm tryin my best but still but i'm having some porblems

thanks alot for the help.

for (Player player:

players)

{

class MyButton extends JButton

{

long startTime = System.currentTimeMillis ();

int index;

ImageIcon icon;

public MyButton (ImageIcon img, int i)

{

icon = img;

index = i;

setPreferredSize (new Dimension (100, 100));

addActionListener (new ActionListener ()

{

public void actionPerformed (ActionEvent actionEvent)

{

// 1

/* Create and add a prompt and then a text field */

if (getIcon () == null)

{

setIcon (icon);

if (buttonShowingIndex > -1)

{

if (icon != button [buttonShowingIndex].getIcon ())

{

final int bsi = buttonShowingIndex;

ActionListener al = new ActionListener ()

{

public void actionPerformed (ActionEvent actionEvent)

{

MyButton.this.setIcon (null);

button [bsi].setIcon (null);

}

}

;

javax.swing.Timer timer = new javax.swing.Timer (450, al);

timer.setRepeats (false);

timer.start ();

}

buttonShowingIndex = -1;

}

else

buttonShowingIndex = index;

//time calculation

long endTime = System.currentTimeMillis ();

long difference = ((endTime - startTime) / 1000) + 2;

timez [i] = difference;

i++;

}

}

}

);

}

}

}

Message was edited by:

Nadal_Federer

Nadal_Federera at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...
# 5
Maybe I'm going crazy, but I don't see any loops in there at all. I'm not psychic, and Hippolyte's borrowing my crystal ball... so, I don't know what you're trying to do :).
kevjavaa at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...
# 6

hey

sry abt that earlier

here's what i did. i tried to use the For each loop but i could not get it. so i thought i would try the for loop. but even that does not work. i have the for loop in comments in the program. so that u could find it.

the "gamesRun" variable is the variable which contains the number as to the number of people who are playing the game

class MyButton extends JButton

{

long startTime = System.currentTimeMillis ();

int index;

ImageIcon icon;

// for (int i = 0 ; i < gamesRun ; i++)

// {

public MyButton (ImageIcon img, int i)

{

icon = img;

index = i;

setPreferredSize (new Dimension (100, 100));

addActionListener (new ActionListener ()

{

public void actionPerformed (ActionEvent actionEvent)

{

// 1

/* Create and add a prompt and then a text field */

if (getIcon () == null)

{

setIcon (icon);

if (buttonShowingIndex > -1)

{

if (icon != button [buttonShowingIndex].getIcon ())

{

final int bsi = buttonShowingIndex;

ActionListener al = new ActionListener ()

{

public void actionPerformed (ActionEvent actionEvent)

{

MyButton.this.setIcon (null);

button [bsi].setIcon (null);

}

}

;

javax.swing.Timer timer = new javax.swing.Timer (450, al);

timer.setRepeats (false);

timer.start ();

}

buttonShowingIndex = -1;

}

else

buttonShowingIndex = index;

//time calculation

long endTime = System.currentTimeMillis ();

long difference = ((endTime - startTime) / 1000);

timez [0] = difference;

}

}

}

);

//

// }

}

}

i also have another small piece of code to get the "MyButton" to run.

MyButton[] button = new MyButton [36];

ImageIcon[] icons = new ImageIcon [button.length];

the program that i am making is the memory game where u have to match the cards. the code i have put up is the part responsible for checking to see if the user has clicked on the two right cards.

i use ImageIcon to get the pics

// icons [0] = new ImageIcon (getClass ().getResource ("image1.gif"));

and then to add the pics to the screen i use

:

for (int x = 0 ; x < button.length ; x++)

{

button [x] = new MyButton (icons [x], x);

mainPanel.add (button [x]);

}

getContentPane ().add (mainPanel);

pack ();

i hope this xplains wat i'm trying to do. i am trying to finish this program by thrusday and so yur help would be rely appreciated.

thanks.

Nadal_Federera at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...
# 7

No we are still confused about what you are trying to do exactly.

That code I posted earlier was just an example to show you what your code MIGHT look like if you were to implement a For Each loop construct.

Also you cannot just place a For Each loop construct in the class body like that. It needs to be within the scope of a method or constructor.

The players variable is just an example of an Array or Collection object of some kind. The player variable is just a reference to a Player object in that collection.

I can't just place that code in for you because the only code I see is the code for your MyButton class, which looks like it is supposed to be your card that you flip over.

The only functionality within your card right now is to just flip the card over and show what its contents are. There is no functionality that I see where after two cards are flipped that there values are compared.

You are either not showing all of your code or you have a lot more to do before Thursday.

Your players collection is likely in an object that HAS A MyButton object, like your JFrame or JPanel. You want to check for two matching shown values in your JPanel class and if they are equal then likely remove them from the screen and add points to a players score? Else, you would flip them back over and it is the next persons turn.

That is all the more I can help you without seeing the rest of your code.

maple_shafta at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...
# 8

hey man,

thanks for taking the trouble for helping me.

i have put the whole part of my program below. what u mentioned earlier was part right. the "MyButton" class flips over the two cards which were clicked by the user and then if they are right it leaves the cards on the table with the pics. and if they are wrong then the pics dissppear and the user has to choose two more cards again.

the "players" array is an array which contains the names of the people who are playing the game. i get those values from another class called "Score" and then i transfer the array to the "MemoryMatch" class.

..and for the points i was thinking that i would find the time required by the user to finish the game and subtract the time in seconds from a base value of 500.

hope this helps.

thanks

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.util.*;

class MemoryMatch extends JFrame

{

MyButton[] button = new MyButton [36];

ImageIcon[] icons = new ImageIcon [button.length];

int buttonShowingIndex = -1;

int time = 0;

long startTime, endTime;

static int gamesRun;

static boolean runs;

JPanel contentPanel;

JPanel mainPanel;

JLabel text;

JTextField grade1;

long[] timez = new long [5];

static String[] players = {"", "", "", "", ""};

//delay method

public static void delay (int num)

{

try

{

Thread.sleep (num);

}

catch (InterruptedException e)

{

}

}

public MemoryMatch ()

{

icons [0] = new ImageIcon (getClass ().getResource ("image1.gif"));

icons [1] = new ImageIcon (getClass ().getResource ("image2.gif"));

icons [2] = new ImageIcon (getClass ().getResource ("image3.gif"));

icons [3] = new ImageIcon (getClass ().getResource ("image4.gif"));

icons [4] = new ImageIcon (getClass ().getResource ("image5.gif"));

icons [5] = new ImageIcon (getClass ().getResource ("image6.gif"));

icons [6] = new ImageIcon (getClass ().getResource ("image7.gif"));

icons [7] = new ImageIcon (getClass ().getResource ("image8.gif"));

icons [8] = new ImageIcon (getClass ().getResource ("image9.gif"));

icons [9] = new ImageIcon (getClass ().getResource ("image10.gif"));

icons [10] = new ImageIcon (getClass ().getResource ("image11.gif"));

icons [11] = new ImageIcon (getClass ().getResource ("image12.gif"));

icons [12] = new ImageIcon (getClass ().getResource ("image13.gif"));

icons [13] = new ImageIcon (getClass ().getResource ("image14.gif"));

icons [14] = new ImageIcon (getClass ().getResource ("image15.gif"));

icons [15] = new ImageIcon (getClass ().getResource ("image16.gif"));

icons [16] = new ImageIcon (getClass ().getResource ("image17.gif"));

icons [17] = new ImageIcon (getClass ().getResource ("image18.gif"));

icons [18] = icons [0];

icons [19] = icons [1];

icons [20] = icons [2];

icons [21] = icons [3];

icons [22] = icons [4];

icons [23] = icons [5];

icons [24] = icons [6];

icons [25] = icons [7];

icons [26] = icons [8];

icons [27] = icons [9];

icons [28] = icons [10];

icons [29] = icons [11];

icons [30] = icons [12];

icons [31] = icons [13];

icons [32] = icons [14];

icons [33] = icons [15];

icons [34] = icons [16];

icons [35] = icons [17];

Collections.shuffle (Arrays.asList (icons));

setDefaultCloseOperation (EXIT_ON_CLOSE);

contentPanel = new JPanel ();

contentPanel.setBorder (BorderFactory.createEmptyBorder (500, 500, 10, 10));

mainPanel = new JPanel ();

mainPanel.setBorder (BorderFactory.createEmptyBorder (500, 500, 10, 10));

mainPanel.setBackground (Color.white);

mainPanel.setLayout (new GridLayout (6, 6));

for (int x = 0 ; x < button.length ; x++)

{

button [x] = new MyButton (icons [x], x);

mainPanel.add (button [x]);

}

getContentPane ().add (mainPanel);

pack ();

}

public static int pushPlayers (String[] p)

{

players = p;

int game = 5;

if (players [0].equals (""))

{

game = game - 1;

}

if (players [1].equals (""))

{

game = game - 1;

}

if (players [2].equals (""))

{

game = game - 1;

}

if (players [3].equals (""))

{

game = game - 1;

}

if (players [4].equals (""))

{

game = game - 1;

}

System.out.println (game);

gamesRun = game;

return game;

}

class MyButton extends JButton

{

long startTime = System.currentTimeMillis ();

int index;

ImageIcon icon;

// for (int i = 0 ; i < gamesRun ; i++)

// {

public MyButton (ImageIcon img, int i)

{

icon = img;

index = i;

setPreferredSize (new Dimension (100, 100));

addActionListener (new ActionListener ()

{

public void actionPerformed (ActionEvent actionEvent)

{

// 1

/* Create and add a prompt and then a text field */

if (getIcon () == null)

{

setIcon (icon);

if (buttonShowingIndex > -1)

{

if (icon != button [buttonShowingIndex].getIcon ())

{

final int bsi = buttonShowingIndex;

ActionListener al = new ActionListener ()

{

public void actionPerformed (ActionEvent actionEvent)

{

MyButton.this.setIcon (null);

button [bsi].setIcon (null);

}

}

;

javax.swing.Timer timer = new javax.swing.Timer (450, al);

timer.setRepeats (false);

timer.start ();

}

buttonShowingIndex = -1;

}

else

buttonShowingIndex = index;

//time calculation

long endTime = System.currentTimeMillis ();

long difference = ((endTime - startTime) / 1000);

timez [0] = difference;

}

}

}

);

//

// }

}

}

public static void main (String[] args)

{

// JFrame.setDefaultLookAndFeelDecorated (true);

// Score myGrades = new Score (myMemoryMatch);

// //Score

delay (5000);

MemoryMatch myMemoryMatch = new MemoryMatch ();

//running of main game

myMemoryMatch.setVisible (true);

//transferring to the array

for (int i = 0 ; i < myMemoryMatch.players.length ; i++)

{

// show that the variable has been updated here

players [i] = myMemoryMatch.players [i];

}

for (int i = 0 ; i < myMemoryMatch.players.length ; i++)

{

// show that the variable has been updated here

System.out.println (players [i]);

}

}

}

Nadal_Federera at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...
# 9

Ah! It is all starting to come together now.

The only other issue I feel that you have though is how you plan on keeping scores with players.

The way you are wanting to do it is confusing and prone to error.

The best way would be to create a whole new Player class like in my For Each loop example.

This would be good code for your Player class.

class Player {

private String name = null;

private Integer score = null;

public Player(String name) {

this.name = name;

this.score = new Integer(500);

}

public void setName(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setScore(Integer score) {

this.score = score;

}

public Integer getScore() {

return score;

}

public boolean equals(Object o) {

if (o instanceof String) {

String arg = (String)o;

return arg.equals(this);

} else {

return false;

}

}

}

It is just a simple Bean object that organizes your data in a meaningful way. A Player generally has two defining characteristics in a game, a name for him or her to be indentified with, and a score.

Rather than use a String array and a seperate integer to determine score, you can have one array of Player objects that have their own names and scores.

Message was edited by:

maple_shaft

maple_shafta at 2007-7-12 17:38:03 > top of Java-index,Java Essentials,Java Programming...