[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

JAVA

Posted on 2011-04-22
68
Medium Priority
?
445 Views
Last Modified: 2012-05-11
Please perform the tasks below in java.

1)  write a shuffle method to put into a random order a given array containing a deck of playing cards (Ace through King, all four suits).

2)   write a Deal method to give out 5 cards to each of the players
   
3)   Provide unit tests to verify the code.
0
Comment
Question by:JavaTears
  • 34
  • 33
67 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35451357

If this is hometask please write some draft - we can help
you to correct and debug. We are  not supposed to do your homework for you

I can recommed that you google card deck Java - I'm sure you'll
find some initial drafts for programmin the card deck

0
 

Author Comment

by:JavaTears
ID: 35451724
no, it not homework;  I did not like what I saw on google,
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35451755


I think this contains code for
http://www.dreamincode.net/forums/topic/110380-deck-of-cards-using-various-methods/
for all (maybe almost all) of your tasks even in several
variants.

I like the one which is based inthe ArrayList
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:JavaTears
ID: 35451795
But it does not have that of a deal method where card are given to the players...or did I miss something?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35451803
But it does have a method of drawing one card from the deck.
From that you can draw five cards to each player, I guess.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35453031


What I would suggest, as one of the ways, you can
create another class called Player and this class could have,
say an instance variable String Name, and  another
instance variable - say ArrayList of cards - those are the cards which this player has.

And then we can create class Game, where in contructor you should
create say an array of four players, a deck of cards,
shuffle the deck.
And you could have a  method there called Deal,
where you would use drawCard  method of the
Deck class five times for each of the players.
It could return the number of cards left in the Deck.

Then you can write a test class and test, say,
that the total number of cards left in the deck,
as returned by the Deal method is 32.
Something like that may probably satisfy your
requirements.

Write some draft, I can look at it.
If you have questions, let me know,
we can think of it together.




0
 

Author Comment

by:JavaTears
ID: 35453515
Thanks for the suggestion, I will send what I have to you a little later.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35453517
OK
0
 

Author Comment

by:JavaTears
ID: 35455125
my shuffle is not working when I swap
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35455170
what means swap?
And how do you know it is not working?
Are you using the code from taht example?
0
 

Author Comment

by:JavaTears
ID: 35456806
Hello, I am yet to hear from you. I sent you some code of mine. Still waiting to see what you can do to improve it.
0
 

Author Comment

by:JavaTears
ID: 35456965
Thanks...please look over the code.


import java.util.ArrayList;
//import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author Owner
 *
 */
public class CardGame {
	
	private static String[] suit = {"hearts", "spades", "diamonds", "clubs"};
	private static String[] rank  = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", 

"Jack", "Queen", "King"};
	private static int cardsDealt;
	private static int numOfPlayers;
	private Random randomly;
	private int cardAthand;
	List<String> deck  = new ArrayList<String>();
	
		
	public CardGame(){
		
		for (int s = 0; s < suit.length; s++){
			for (int r = 0; r < rank.length; r++){
				deck.add(rank[r] + " of " + suit[s]);
		    }
			System.out.println("show unshuffled decks: " + deck);		
	    }

		shuffleDeck(deck);
		dealFive();
    }
	
	private void shuffleDeck(List<String> deck) {
		// TODO Auto-generated method stub
		List<Integer> theArrayList = new ArrayList<Integer>();
		int[] card = new int[52];
		int index;

		//Collections.shuffle(deck);
		System.out.println("Shuffled = deck " + deck);
		//System.out.println("deckSize = " + deck.size()+ " " + (deck.size() - t));
		System.out.println("Shuffled = ");
		for (int i = 0; i < deck.size(); i++){
			index =  randomly.nextInt(deck.size());
			int temp = card[i];
			card[i] = card[index];
			card[index] = temp;
		}
	}

	public int dealFive(){
		 
		if (numOfPlayers * cardsDealt > deck.size()){
			System.out.println("Few Cards");
		return 0;
		}
		for (int c = 0; c < cardsDealt; c++){
			//???
	}
		return cardAthand;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		CardGame cardgames = new CardGame();
	}
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35457090


You know what - I'd suggest to return to the variant
we saw in that example - you rather want to create Card class and
make your deck as arraylist  of Card objects
This idea of strings as card is definitely not very good.
Then by the way you can use their shuffle method and
many othe things and then write only additional
code which you need.

In the end in most of Card games you need to check which card trumps which - so
to have them as sytrings would be very inconvenient.

It is good to use whatever reasonable which people already created.
Return to that example

 
 
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35457204
Yes, I think they have good code - in particular the
variant where they use ArrayLists.
You can take it as a basis - add some Game class, Player class, deal method, etc.
0
 

Author Comment

by:JavaTears
ID: 35457258
I do not know how the deal method should be. ...clueless!!!
0
 

Author Comment

by:JavaTears
ID: 35457270
Btw, There are 2 classes 1) deck and 2) card. I do not want to have two classes, instead, I need 2 methods
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35457282
Well, I thinlk it makes all the sense in the wirlkd to have two classes
0
 

Author Comment

by:JavaTears
ID: 35457294
I want a class with the deck of cards, and within, I will have a method to shuffle it and another one to make the deal. I do not want to loose focus of my initial question. Why do I need two classes to do what I want to accomplish? Also, I tried running the deck class, but it failed.

Instead of going back and forth, can you tell me what I can do to improve the code I sent previously?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35457518

Your  code was by no means shuffling.
I modified it, so that at least the shuffle works.


import java.util.ArrayList;
//import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author Owner
 *
 */
public class CardGame {

	private static String[] suit = {"hearts", "spades", "diamonds", "clubs"};
	private static String[] rank  = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10",

"Jack", "Queen", "King"};
	private static int cardsDealt;
	private static int numOfPlayers;
	private Random randomly;
	private int cardAthand;
	List<String> deck  = new ArrayList<String>();


	public CardGame(){

		for (int s = 0; s < suit.length; s++){
			for (int r = 0; r < rank.length; r++){
				deck.add(rank[r] + " of " + suit[s]);
		    }
			System.out.println("show unshuffled decks: " + deck);
	    }

		shuffleDeck();
		dealFive();
    }

	private void shuffleDeck() {
		// TODO Auto-generated method stub
		List<String> theArrayList = new ArrayList<String>();
		int[] card = new int[52];
		int index;

        for(int j=0; j<52; j++){
            card[j]= j;
        }

		//Collections.shuffle(deck);
		System.out.println("Shuffled = deck " + deck);
		//System.out.println("deckSize = " + deck.size()+ " " + (deck.size() - t));
		System.out.println("Shuffled = ");
        randomly = new Random((new java.util.Date()).getTime());
		for (int i = 0; i < deck.size(); i++){
			index =  randomly.nextInt(deck.size());
			int temp = card[i];
			card[i] = card[index];
			card[index] = temp;
		}
          for(int j=0; j<52; j++){
              String s = deck.get(card[j]);

        
               theArrayList.add(s);
          }
        deck =  theArrayList;
        System.out.println("Shuffled = "+ deck);
	}

	public int dealFive(){

		if (numOfPlayers * cardsDealt > deck.size()){
			System.out.println("Few Cards");
		return 0;
		}
		for (int c = 0; c < cardsDealt; c++){
			//???
	}
		return cardAthand;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		CardGame cardgames = new CardGame();
	}
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35457552

This is their code working very nicely - there was a very slight mistake - temp
variable was not declared - other than that their code looks OK
and you certainly don't want keep cards as array of strings

package javacards;

public class Card
{
	private int rank, suit;

	private static String[] suits = { "hearts", "spades", "diamonds", "clubs" };
	private static String[] ranks  = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };


	Card(int suit, int rank)
	{
		this.rank=rank;
		this.suit=suit;
	}

	public @Override String toString()
	{
		  return ranks[rank] + " of " + suits[suit];
	}

	public int getRank() {
		 return rank;
	}

	public int getSuit() {
		return suit;
	}

}

Open in new window




package javacards;

import java.util.Random;
import java.util.ArrayList;

public class Deck {
	private ArrayList<Card> cards;

	 Deck()
	{
		cards = new ArrayList<Card>();
		for (int a=0; a<=3; a++)
		{
			for (int b=0; b<=12; b++)
			 {
			   cards.add( new Card(a,b) );
			 }
		}
	}

	public Card drawFromDeck()
	{
		Random generator = new Random();
		int index= generator.nextInt( cards.size() );
		return cards.remove(index);
	}

	 public int getTotalCards()
	{
		return cards.size();
	}

    public void reshuffle(){
        Random generator = new Random();

                
        int index_1, index_2;
        for (int i=0; i<100; i++)
        {
            index_1 = generator.nextInt( cards.size() - 1 );
            index_2 = generator.nextInt( cards.size() - 1 );

            Card temp = (Card) cards.get( index_2 );
            cards.set( index_2 , cards.get( index_1 ) );
            cards.set( index_1, temp );
        }
 


    }

    public String toString(){
        String s = "";
      for(int j=0; j<cards.size(); j++){
             s += cards.get(j).toString() + ",";
      }
        return s;
    }

    public static void main(String [] args){
        Deck d = new Deck();
        System.out.println("deck initial: " + d);
        d.reshuffle();
         System.out.println("deck reshuffled: " + d);

    }

}

Open in new window



deck initial: Ace of hearts,2 of hearts,3 of hearts,4 of hearts,5 of hearts,6 of hearts,7 of hearts,8 of hearts,9 of hearts,10 of hearts,Jack of hearts,Queen of hearts,King of hearts,Ace of spades,2 of spades,3 of spades,4 of spades,5 of spades,6 of spades,7 of spades,8 of spades,9 of spades,10 of spades,Jack of spades,Queen of spades,King of spades,Ace of diamonds,2 of diamonds,3 of diamonds,4 of diamonds,5 of diamonds,6 of diamonds,7 of diamonds,8 of diamonds,9 of diamonds,10 of diamonds,Jack of diamonds,Queen of diamonds,King of diamonds,Ace of clubs,2 of clubs,3 of clubs,4 of clubs,5 of clubs,6 of clubs,7 of clubs,8 of clubs,9 of clubs,10 of clubs,Jack of clubs,Queen of clubs,King of clubs,
deck reshuffled: 3 of hearts,King of diamonds,4 of clubs,Ace of spades,Queen of diamonds,8 of diamonds,9 of clubs,3 of clubs,2 of hearts,9 of hearts,Jack of diamonds,7 of clubs,Queen of spades,Ace of clubs,10 of hearts,6 of clubs,8 of hearts,Queen of hearts,Jack of spades,2 of diamonds,8 of spades,9 of spades,Jack of clubs,5 of hearts,4 of spades,9 of diamonds,King of hearts,7 of diamonds,Jack of hearts,7 of hearts,10 of spades,5 of spades,3 of diamonds,3 of spades,Ace of diamonds,5 of clubs,Ace of hearts,6 of hearts,Queen of clubs,2 of clubs,5 of diamonds,6 of diamonds,King of spades,4 of hearts,2 of spades,8 of clubs,10 of clubs,6 of spades,4 of diamonds,10 of diamonds,7 of spades,King of clubs,

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35457561

By the way, this is the output of your code
after I modified it substantially (as of posting ID:35457552; forgot
to post it together with the code):

show unshuffled decks: [Ace of hearts, 2 of hearts, 3 of hearts, 4 of hearts, 5 of hearts, 6 of hearts, 7 of hearts, 8 of hearts, 9 of hearts, 10 of hearts, Jack of hearts, Queen of hearts, King of hearts]
show unshuffled decks: [Ace of hearts, 2 of hearts, 3 of hearts, 4 of hearts, 5 of hearts, 6 of hearts, 7 of hearts, 8 of hearts, 9 of hearts, 10 of hearts, Jack of hearts, Queen of hearts, King of hearts, Ace of spades, 2 of spades, 3 of spades, 4 of spades, 5 of spades, 6 of spades, 7 of spades, 8 of spades, 9 of spades, 10 of spades, Jack of spades, Queen of spades, King of spades]
show unshuffled decks: [Ace of hearts, 2 of hearts, 3 of hearts, 4 of hearts, 5 of hearts, 6 of hearts, 7 of hearts, 8 of hearts, 9 of hearts, 10 of hearts, Jack of hearts, Queen of hearts, King of hearts, Ace of spades, 2 of spades, 3 of spades, 4 of spades, 5 of spades, 6 of spades, 7 of spades, 8 of spades, 9 of spades, 10 of spades, Jack of spades, Queen of spades, King of spades, Ace of diamonds, 2 of diamonds, 3 of diamonds, 4 of diamonds, 5 of diamonds, 6 of diamonds, 7 of diamonds, 8 of diamonds, 9 of diamonds, 10 of diamonds, Jack of diamonds, Queen of diamonds, King of diamonds]
show unshuffled decks: [Ace of hearts, 2 of hearts, 3 of hearts, 4 of hearts, 5 of hearts, 6 of hearts, 7 of hearts, 8 of hearts, 9 of hearts, 10 of hearts, Jack of hearts, Queen of hearts, King of hearts, Ace of spades, 2 of spades, 3 of spades, 4 of spades, 5 of spades, 6 of spades, 7 of spades, 8 of spades, 9 of spades, 10 of spades, Jack of spades, Queen of spades, King of spades, Ace of diamonds, 2 of diamonds, 3 of diamonds, 4 of diamonds, 5 of diamonds, 6 of diamonds, 7 of diamonds, 8 of diamonds, 9 of diamonds, 10 of diamonds, Jack of diamonds, Queen of diamonds, King of diamonds, Ace of clubs, 2 of clubs, 3 of clubs, 4 of clubs, 5 of clubs, 6 of clubs, 7 of clubs, 8 of clubs, 9 of clubs, 10 of clubs, Jack of clubs, Queen of clubs, King of clubs]
Shuffled = deck [Ace of hearts, 2 of hearts, 3 of hearts, 4 of hearts, 5 of hearts, 6 of hearts, 7 of hearts, 8 of hearts, 9 of hearts, 10 of hearts, Jack of hearts, Queen of hearts, King of hearts, Ace of spades, 2 of spades, 3 of spades, 4 of spades, 5 of spades, 6 of spades, 7 of spades, 8 of spades, 9 of spades, 10 of spades, Jack of spades, Queen of spades, King of spades, Ace of diamonds, 2 of diamonds, 3 of diamonds, 4 of diamonds, 5 of diamonds, 6 of diamonds, 7 of diamonds, 8 of diamonds, 9 of diamonds, 10 of diamonds, Jack of diamonds, Queen of diamonds, King of diamonds, Ace of clubs, 2 of clubs, 3 of clubs, 4 of clubs, 5 of clubs, 6 of clubs, 7 of clubs, 8 of clubs, 9 of clubs, 10 of clubs, Jack of clubs, Queen of clubs, King of clubs]
Shuffled = 
Shuffled = [9 of hearts, King of diamonds, 10 of spades, 2 of spades, 3 of spades, 4 of spades, Jack of hearts, 4 of diamonds, 10 of diamonds, 8 of hearts, 6 of diamonds, Ace of clubs, 7 of spades, Jack of spades, 6 of hearts, 2 of hearts, 6 of spades, 8 of spades, 2 of diamonds, King of spades, Jack of clubs, 3 of diamonds, 7 of diamonds, 5 of diamonds, 4 of clubs, Queen of clubs, 6 of clubs, 3 of hearts, 8 of diamonds, 3 of clubs, 5 of spades, 10 of hearts, Ace of hearts, Ace of diamonds, Ace of spades, 5 of hearts, Queen of spades, Queen of hearts, 2 of clubs, 7 of hearts, 9 of diamonds, 8 of clubs, 9 of spades, 4 of hearts, Queen of diamonds, 7 of clubs, King of hearts, Jack of diamonds, 5 of clubs, 9 of clubs, 10 of clubs, King of clubs]

Open in new window

0
 

Author Comment

by:JavaTears
ID: 35457597
THANKS  a lot. I got lost after the swapping.

Do you think that my logic with deal is completely wrong? Please let me know
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35457612

I think your method dealFive() does not make much other than checking
the total number of cards  - that's why I'm saying
you should create Player object and players array and dealing
should accomplish two things - it needs to make sure that five cards
are assigned to each player, and also make sure that these cards are removed
from the deck (see drawCard() method from their Deck class; if you just multpily
this method and alsoo add assigning cards to players - that would be the real dealing method).
0
 

Author Comment

by:JavaTears
ID: 35457842
Please tell me why dealFive is populating the array with the same value.  I have attached my code.

Please let me know what is wrong with it!!


Shuffle-Problem.txt
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35457875
More or les the same issue that you had
with shuffle method before.

You use the the random generator to generate arbitrary index value,
let's say that you remove from the deck correctly the card with
this arbitrary index, but then when you create DealsArrayList,
your arbitrary determined index plays no role at all - you just go through
cards in their natural order.
And, as you have only initializes Dealscard array, but have not
populated it, all deck.get(Dealscard[j]) in fact probably refer to one and the same
card deck.get(0).

0
 

Author Comment

by:JavaTears
ID: 35457893
hmm...let me see what I can do to try and fix the problem; I will let you know soon what is going on. Btw, thanks for your time, I appreciate your assistance but I am not done yet...hahah
0
 

Author Comment

by:JavaTears
ID: 35458003
Still working on Deal...but most importantly, I normally do my test by debugging. But can you PLEASE tell me how to do unit test for the shuffle? Like I said, I've not done it before.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35458030
Well, the only thing I can think of - you can add to your deck staic method


pubic static boolean decksDifferent(Deck d1, Deck d2){
for(int j=0; j<52; j++){
if(!d1.getCard(j).equals(d2.getCard(j)))return true;
}
}

(you would also need to add instance method
public String  getCard(int j) {
return card[j];
}
)

Then you could have your deck before shuffle and after shuffle
assertTrue(decksDifferent(deck1, deck2))

Don't know if something simpler could be invented
Even this is theoreticlly not right as they potentially can happen to be the same

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35458032


it actually should be like that:
pubic static boolean decksDifferent(Deck d1, Deck d2){
for(int j=0; j<52; j++){
if(!d1.getCard(j).equals(d2.getCard(j)))return true;
}
return false;
}
0
 

Author Comment

by:JavaTears
ID: 35458048
Interesting! Does it mean that I have to perform the unit test in the same place where I have the shuffle program? So do you mean that I do not have to have another program to do the testing? Please advice.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35458080
It does not matter - normally you would probably make separate class, but all your classes
which you are testing should of course be accesible - you probably need to make
a bunch of your methods public for that purpose - junit testing is in general designed
for testing pblic, not private methods

CardGame cg1 = new CardGame();
ArrayList deck1 = cg1.getCards();  <---- you want to add such method allso
cg1.shuffleDeck();  <--- this needs to be public for that
ArrayList deck2 = cg1.getCards();  
assertTrue(...)
...

So their design. as I mentioned many times,  for this purpose would have been
also much more convenient

You can read more or less the same general opinion  from
http://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods

below

When I have private methods in a class that is sufficiently complicated that I feel the need to test the private methods directly, that is a code smell: my class is too complicated.

My usual approach to addressing it is to tease out a new class that contains the interesting bits. Often, this method and the fields it interacts with, and maybe another method or two can be extracted in to a new class.



 
0
 

Author Comment

by:JavaTears
ID: 35458106
Good to know, but if I change the methods private to public after the unit test do I have to go back to the program and change the access modifiers back to what I want them to be?

Secondly, if I change things to static for the unit test, will it not change my code especially if I instantiated something?

You have been of great assistance and I must say THANK YOU for the help!!
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35458113
if yoou change mthods to public there is no need to change them back afterwards - at least
in my opnion.

I didn't suggest to change existing methods to static, I suggested to add a new static
method - specifically for testing purposes. There is certainly no need to delete
this method after testing. That is the point of unit testing - in theory, suppose you once decide to
improve your shuffle method - you'll still use the same framework and the same methods for testing.
0
 

Author Comment

by:JavaTears
ID: 35458140
So the instance method is only for testing? Ok.

I understand what you wrote about adding static methods for testing; great.

I am going to try it out and let you know how successful I was. Thanks
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35458147
I meant, STATIC method only for testing;
some of instance methods, which you want to test, you'll have to make public

0
 

Author Comment

by:JavaTears
ID: 35458153
ok..understood. thanks
0
 

Author Comment

by:JavaTears
ID: 35460855
In order to run this program on another computer do I have to copy the .jar file and source file only?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35460966

In order to run it you don't need source files, you need only compuiled classes, either
packaged in a jar (which may or may not contain the sources - as you like)
or say all classes in a folder.
Source files are need ony for frther modification of the program,
in order to run it you need only classes
0
 

Author Comment

by:JavaTears
ID: 35461052
If I were to email the .class files via attachment, will that work also?

In addition, please tell me how to package something in a .jar file
0
 

Author Comment

by:JavaTears
ID: 35461422
I put this right before my shuffle and it is not working at all, what can I do to fix it please?

pubic static boolean decksDifferent(Deck d1, Deck d2){
for(int j=0; j<52; j++){
if(!d1.getCard(j).equals(d2.getCard(j)))return true;
}
}

(you would also need to add instance method
public String  getCard(int j) {
return card[j];
}
)


0
 
LVL 47

Expert Comment

by:for_yan
ID: 35461474
What means "it is not workiking at all"  -- how do you want it tow work - it needs to be used in the
testing code

Are you using IDE - they should have option for creating jar files

You can send casses as attahments
0
 

Author Comment

by:JavaTears
ID: 35461717
This is what I have above my shuffle method. Because I do not have a deck class I used the class that I inserted the name of the class I am working with in decksDifferent. But nothing is happening.

public static boolean decksDifferent(CardGame d1, CardGame d2){
                  for(int j=0; j<52; j++){
                        System.out.println("\n" + "Hello Testing Testing Testing ");
                  if(!d1.getCard(j).equals(d2.getCard(j)))return true;
                  System.out.println("\n" + "1 Hello Testing Testing Testing ");
                  }
                  System.out.println("\n" + "2 Hello Testing Testing Testing ");
                  return false;
                  }
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35461756

But nothing should be happening untill you call this method,
and you will call this method from your test code.

Or if you want to "test" this test method from
right here you can create these CardGame objects right in
the main method and then call this method from the main()

When you just adding a new method to the class, nothing happens
until you call it.




0
 
LVL 47

Expert Comment

by:for_yan
ID: 35461772
Weh you create your testing environment
you 'll suppsoedly have a test method there which will isntatiate
your GardGames's objects and when you
call in that test method assertTrue(Gamecard.decksDifferent(....))
then this your static method woul be called
0
 

Author Comment

by:JavaTears
ID: 35461834
Since I have just one class, I thought I will do the test right after my shuffle method? Am I wrong to think like that? If you say yes, then the next thing is:

You want me to have call e.g decksDifferent(d1, d2)
 
If not please help because I am lost since I have never done unit test before
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35462084
Normally you create and excute a separate class where you run your tests
something like that:


import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class CardTest {
 @Test
 public void testShuffle() {
CardGame d1 = new CardGame();
CardGame d2 = new cardGame();
d2.shuffleDeck();
assertTrue(decksDifferent(d1, d2));
   }
}

read somewhere about Unit testing
For raeal life for this case you definitely don't need it
If this is still your exercise and you need to present it to someone
the read about it, say

http://junit.sourceforge.net/doc/cookbook/cookbook.htm

http://www.javabeat.net/tips/159-junit-40-example.html

and there are of course tons of other places




0
 

Author Comment

by:JavaTears
ID: 35462964
Oh my! Struggling with this now. Please HELP!!

I added above shuffle and change shuffle to void shuffle()

public static boolean decksDifferent(CardGame d1, CardGame d2){
                  for(int j=0; j<52; j++){
                        System.out.println("\n" + "Hello Testing Testing Testing ");
                  if(!d1.getCard[j].equals(d2.getCard(j)))return true;
                  System.out.println("\n" + "1 Hello Testing Testing Testing ");
                  }
                  System.out.println("\n" + "2 Hello Testing Testing Testing ");
                  return false;
                  }

Then I also added above the main the code below
public String getCard(int j) {
            String[] card = this.suit;
            System.out.println("Done with Unit Testing");
            return card[j];
      }


Lastly, I created a unit test called GameTest
package cardsPackage;

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

      public class CardGameTest {
       @Test
       public void testShuffleDeck() {
      CardGame d1 = new CardGame();
      CardGame d2 = new CardGame();
      d2.shuffleDeck();
      assertTrue(decksDifferent(d1, d2));
         }

      private void assertTrue(Object decksDifferent) {
            // TODO Auto-generated method stub
            
      }

      private Object decksDifferent(CardGame d1, CardGame d2) {
            // TODO Auto-generated method stub
            return null;
      }
      }
But I keep having error messages when I run the unitTest.
e.g.

Class not found cardsPackage.CardGameTest
java.lang.ClassNotFoundException: cardsPackage.CardGameTest
      at java.net.URLClassLoader$1.run(Unknown Source)
      at java.security.AccessController.doPrivileged(Native Method)
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35463026
One thing that you don't need to define yourself assertTrue,
I think it is something Assert.asserTrue(...)
you have it at the top - so don't redefine it - just use it - I think it is enought
to import class Assert - we usually import classe, but anyway lookup
how it is done in the example - but you don't find to redefine it

But your error is probably because you should chaeck with packages
If your class is in the package it should be declared both on top of the
class in the code and it should physically reside
inside the folder - do you know how to do it with packages?

Check also with waht command you are starting it - in one of those examples
which I sent you they talk about how to initiate test and it is not always
just running

java className..

read...



0
 

Author Comment

by:JavaTears
ID: 35463120
I declared package cardsPackage;;on top of both codes and I saw it in both files in the the package when  

Secondly, I am just running the junit GameTest class from Eclipse. Is that not what I should do? I really need help.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35463135

Post all your code as it stands now.
When I have time I may look at it
0
 

Author Comment

by:JavaTears
ID: 35463418
It is attached.  Please let me know how to fix it.
CardGame.txt
CardGameTest.txt
0
 

Author Comment

by:JavaTears
ID: 35463675
Please let me know how you are doing with the project. I am still waiting.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35463680
Well, I may try to do it overnight.
0
 

Author Comment

by:JavaTears
ID: 35463725
Ok, if I tried to delete all the unit test in order to make my program work again will that but I am still having
the same error message. Why????

 java.lang.NoClassDefFoundError: cardsPackage/CardGame
Caused by: java.lang.ClassNotFoundException: cardsPackage.CardGame
      at java.net.URLClassLoader$1.run(Unknown Source)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
Exception in thread "main"
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35463777
I don't understand why that could be.
I'm guessing you are doing something wrong with packages.

I'd also suggest that you don't play with it in the meantime, because if I manage to
 correct  your stuff overnight I'll not want to reconcile it with your subsequent changes.
I saw in your code some obvious inconsistencies and wrong things at immediate glance.
Unit testing however is something which requires my time to do, I normally don't do unit testing,
as in my usually one-time projects unit testing has no value at all.
Therefore, I cannot do it right now. I'll try to figure out overnight.
Please, let me know that you are not going to modify it in the meantime,
otherwise it all becomes useless.


 
0
 

Author Comment

by:JavaTears
ID: 35464112
I am not going to modify it at all. I will wait for you.

I never knew that unit testing can change things around for bad if not done well. But I am willing to wait.

Once again, thanks.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35464118
Unit testing cannot change for bad,
but whenever you modify any code there is always probability
to spoil any piece of code
And it ver often happens that while trying to improve
any piece of code I screw up the code in the place
where I least expected
0
 

Author Comment

by:JavaTears
ID: 35464135
Makes sense....
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35465049

This is your unit testing.
I modified your code of the GameCard class a little
bit, in particular removed shuffling from the constructor,
otherwise the testing is not so illustrative.

Now you'll need to have jar file which is called

junit-4.8.2.jar

(not the earlier ones, but this one).

The class and the test code are in different packages.
If you are using IDE, then create package cardsPackage
put there CardGame class, then create package
cardsPackageTest and put there CardGameTest class.

If you are not in IDE but compiling at command prompt
then I suggest that you remove packages from
both classes from the top and from within
the main method in the test class
and put them in one folder -
with packages it is difficult to compile with
command line.



Your modified code:
package cardsPackage;

import java.util.ArrayList;
//import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
* @author Owner
*
*/
public class CardGame {

	private static String[] suit = {"Hearts", "Spades", "Diamonds", "Clubs"};
	private static String[] rank  = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10","Jack", "Queen", "King"};
	private static int cardsDealt;
	private static int numOfPlayers;
	private int cardAthand;
	private Random randomly;

	List<String> deck  = new ArrayList<String>();
	//private Object[] getCard;
	//List<String> deck2  = new ArrayList<String>();

	public CardGame(){

		for (int s = 0; s < suit.length; s++){
			for (int r = 0; r < rank.length; r++){
				deck.add(rank[r] + " of " + suit[s]);
		    }
	    }
		System.out.println("Unshuffled deck: " + deck + "\n");

		//shuffleDeck();

		//dealFive();
    }

/*********           For UnitTest      **********************************/

		//public static boolean shuffleDeck(CardGame d1, CardGame d2){
		 public static boolean decksDifferent(CardGame d1, CardGame d2){
			for(int j=0; j<52; j++){
			//	System.out.println("\n" + "Hello Testing Testing Testing ");
			if(!d1.getCard(j).equals(d2.getCard(j)))return true;
			//System.out.println("\n" + "1 Hello Testing Testing Testing ");
			}
			System.out.println("\n" + "2 Hello Testing Testing Testing ");
			return false;
			}

/**********        End   For UnitTest    ******************************/

	 public void shuffleDeck() {

		List<String> theArrayList = new ArrayList<String>();
		//List<String> DealsArrayList = new ArrayList<String>();
		int[] card = new int[52];
		int index;

        for(int j=0; j<52; j++){
            card[j]= j;
        }
		//Collections.shuffle(deck);
		System.out.println("Shuffling... ");
		randomly = new Random((new java.util.Date()).getTime());
		for (int i = 0; i < deck.size(); i++){
			index =  randomly.nextInt(deck.size());
			int temp = card[i];
			card[i] = card[index];
			card[index] = temp;
		}

		for(int j=0; j<52; j++){
            String s = deck.get(card[j]);
            theArrayList.add(s);
        }
      deck = theArrayList;
      System.out.println("Shuffled deck = "+ deck);
      System.out.println("Deck Size = "+ deck.size());

      //  dealFive dealFive dealFive();
	}


/****************   For UnitTest   ****************************/
	public String getCard(int j) {
		//String[] card = this.suit;
		//System.out.println("Done with Unit Testing");
		return (String)deck.get(j);
	}
/*****************  END For UnitTest  ***********************/


	public static void main(String[] args) {
		// TODO Auto-generated method stub

		CardGame cardgames = new CardGame();
		//Object decksDifferent = new Object();

	}
}

Open in new window



Test :


package cardsPackageTest;

import cardsPackage.CardGame;

import org.junit.Assert;
import org.junit.Test;

public class CardGameTest {

                  @Test
    public void testShuffle(){
    CardGame d1 = new CardGame();
	CardGame d2 = new CardGame();
	d2.shuffleDeck();
	Assert.assertTrue(CardGame.decksDifferent(d1, d2));
	}

    public static void main(String args[]) {
        org.junit.runner.JUnitCore.main("cardsPackageTest.CardGameTest");
      }
    }

Open in new window


if you run CardGameTest as it is, there'll
be no error and you'll see the output:

JUnit version 4.8.2
.Unshuffled deck: [Ace of Hearts, 2 of Hearts, 3 of Hearts, 4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts, 8 of Hearts, 9 of Hearts, 10 of Hearts, Jack of Hearts, Queen of Hearts, King of Hearts, Ace of Spades, 2 of Spades, 3 of Spades, 4 of Spades, 5 of Spades, 6 of Spades, 7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades, Jack of Spades, Queen of Spades, King of Spades, Ace of Diamonds, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds, 5 of Diamonds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds, 9 of Diamonds, 10 of Diamonds, Jack of Diamonds, Queen of Diamonds, King of Diamonds, Ace of Clubs, 2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs, 6 of Clubs, 7 of Clubs, 8 of Clubs, 9 of Clubs, 10 of Clubs, Jack of Clubs, Queen of Clubs, King of Clubs]

Unshuffled deck: [Ace of Hearts, 2 of Hearts, 3 of Hearts, 4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts, 8 of Hearts, 9 of Hearts, 10 of Hearts, Jack of Hearts, Queen of Hearts, King of Hearts, Ace of Spades, 2 of Spades, 3 of Spades, 4 of Spades, 5 of Spades, 6 of Spades, 7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades, Jack of Spades, Queen of Spades, King of Spades, Ace of Diamonds, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds, 5 of Diamonds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds, 9 of Diamonds, 10 of Diamonds, Jack of Diamonds, Queen of Diamonds, King of Diamonds, Ace of Clubs, 2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs, 6 of Clubs, 7 of Clubs, 8 of Clubs, 9 of Clubs, 10 of Clubs, Jack of Clubs, Queen of Clubs, King of Clubs]

Shuffling... 
Shuffled deck = [7 of Spades, 8 of Clubs, 8 of Hearts, 9 of Hearts, Jack of Spades, 6 of Spades, 3 of Spades, 4 of Spades, 8 of Diamonds, 4 of Hearts, 6 of Hearts, Ace of Spades, 6 of Diamonds, 5 of Spades, 3 of Clubs, King of Diamonds, Jack of Clubs, 5 of Clubs, King of Spades, 9 of Spades, 2 of Clubs, 2 of Spades, 9 of Diamonds, 10 of Spades, 5 of Hearts, 7 of Diamonds, 3 of Diamonds, 7 of Clubs, 4 of Clubs, 7 of Hearts, Ace of Hearts, 10 of Clubs, 4 of Diamonds, Queen of Diamonds, Ace of Clubs, 2 of Hearts, 5 of Diamonds, Jack of Hearts, Queen of Spades, 10 of Hearts, Ace of Diamonds, Queen of Hearts, King of Clubs, 2 of Diamonds, Jack of Diamonds, 10 of Diamonds, 3 of Hearts, 6 of Clubs, 8 of Spades, Queen of Clubs, King of Hearts, 9 of Clubs]
Deck Size = 52

Time: 0

OK (1 test)


Process finished with exit code 0

Open in new window



If you comment out line
d2.shuffleDeck();
in the test method, you'll see failure
of the test and the output:

JUnit version 4.8.2
.Unshuffled deck: [Ace of Hearts, 2 of Hearts, 3 of Hearts, 4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts, 8 of Hearts, 9 of Hearts, 10 of Hearts, Jack of Hearts, Queen of Hearts, King of Hearts, Ace of Spades, 2 of Spades, 3 of Spades, 4 of Spades, 5 of Spades, 6 of Spades, 7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades, Jack of Spades, Queen of Spades, King of Spades, Ace of Diamonds, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds, 5 of Diamonds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds, 9 of Diamonds, 10 of Diamonds, Jack of Diamonds, Queen of Diamonds, King of Diamonds, Ace of Clubs, 2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs, 6 of Clubs, 7 of Clubs, 8 of Clubs, 9 of Clubs, 10 of Clubs, Jack of Clubs, Queen of Clubs, King of Clubs]

Unshuffled deck: [Ace of Hearts, 2 of Hearts, 3 of Hearts, 4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts, 8 of Hearts, 9 of Hearts, 10 of Hearts, Jack of Hearts, Queen of Hearts, King of Hearts, Ace of Spades, 2 of Spades, 3 of Spades, 4 of Spades, 5 of Spades, 6 of Spades, 7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades, Jack of Spades, Queen of Spades, King of Spades, Ace of Diamonds, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds, 5 of Diamonds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds, 9 of Diamonds, 10 of Diamonds, Jack of Diamonds, Queen of Diamonds, King of Diamonds, Ace of Clubs, 2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs, 6 of Clubs, 7 of Clubs, 8 of Clubs, 9 of Clubs, 10 of Clubs, Jack of Clubs, Queen of Clubs, King of Clubs]


2 Hello Testing Testing Testing 
E
Time: 0
There was 1 failure:
1) testShuffle(cardsPackageTest.CardGameTest)
java.lang.AssertionError: 
	at org.junit.Assert.fail(Assert.java:91)
	at org.junit.Assert.assertTrue(Assert.java:43)
	at org.junit.Assert.assertTrue(Assert.java:54)
	at cardsPackageTest.CardGameTest.testShuffle(CardGameTest.java:15)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.junit.runners.Suite.runChild(Suite.java:128)
	at org.junit.runners.Suite.runChild(Suite.java:24)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
	at org.junit.runner.JUnitCore.runMain(JUnitCore.java:98)
	at org.junit.runner.JUnitCore.runMainAndExit(JUnitCore.java:53)
	at org.junit.runner.JUnitCore.main(JUnitCore.java:45)
	at cardsPackageTest.CardGameTest.main(CardGameTest.java:19)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)

FAILURES!!!
Tests run: 1,  Failures: 1


Process finished with exit code 1

Open in new window


OK. Now I'm done with it.




0
 

Author Comment

by:JavaTears
ID: 35469252
Thanks.

Please tell what I can do to upgrade to junit-4.8.2.jar since I can not use an earlier version.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35469319
0
 

Author Comment

by:JavaTears
ID: 35469596
Thanks a million!
0
 

Author Comment

by:JavaTears
ID: 35469839
Now that I downloaded it, how do I put it in the correct location?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35469869
How do you use your java ?
Do you have Eclipse, or NetBeans or do you jsut compile from comman line?
0
 

Author Comment

by:JavaTears
ID: 35471594
I use Eclipse IDE
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 35471657
In eclipse you need to add this jar file to your project dependencies
You right click your project, then go to Build Path -> Configure Build Path -> Ad External Jar
and then browse to thsi jar
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn different types of Android Layout and some basics of an Android App.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month17 days, 15 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question