hi.. i'm still new to java and i have a project to work on regarding card games. I want to shuffle the deck but i just can't get it.Shuffling the deck must be alternate each element. I don't know if i'm doing the right thing.
I keep getting a " Exception in thread "main" java.lang.NullPointerException". Thanks!

Here's my code:

import java.io.*;
import java.util.*;

 public class Deck{

		Vector deck; // create a 52-card deck
		 final String[] suit = {"D", "H", "S", "C"};
		 final String[] rank = {"A","K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"};

 		public Deck(){

		// creating a list
		 List<String> list = new ArrayList<String>();
			for (int i = 0; i < suit.length; i++)
			{
	      for (int j = 0; j < rank.length; j++)
	        list.add(rank[j] + suit[i]);
			}
			// convert the array to vector
			Vector deck = new Vector(list);
	
			// access elements
			System.out.println("Initial Deck:"); 
			Enumeration deck1 = deck.elements();	
       	 while (deck1.hasMoreElements())
		   {  
				System.out.println(deck1.nextElement().toString());			 
			}

	}
	
	public void shuffle()throws IOException{
	

		BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
		System.out.println ("Enter the desired number for shuffle: ");
		String temp = br.readLine();
		int count = Integer.parseInt(temp);
	
		
		
	
			for (int b=0; b<=count; b++)
				{
			
				for (int i=1;i<(deck.size())/2;i+=2)
					{    	    
				 	 for (int j=26;j<(deck.size())/2;j+=2)
					 {
				 		Collections.swap(deck, i, j);}
					 } 
				}	System.out.println("Shuffled Deck:\n" + deck);
	}
			
			 


		
		public static void main (String[] args) throws IOException{
				Deck cardeck = new Deck();
				cardeck.shuffle();	
}
}

An NPE provides a Line number in the exception messgae, what is it?

An NPE provides a Line number in the exception messgae, what is it?

I've already fixed my previous problem so now this is what i got. i think i must be wrong on the swapping part..

What do you "get now"? And the error message still shows you exactly where, so where?

Just a small hint here: think about a Card class with instance variables for suit and rank (which ideally would be enums). A deck is then a simple array or Collection of Cards.

Exception in thread "main" java.lang.NullPointerException
at Deck.shuffle(Deck.java:46)
at Deck.main(Deck.java:61)


That's after I place the input for the number of shuffles...

See the "Collections" "shuffle" method, maybe?

But, line 20 is your real problem. There you declare and define "deck" as a local variable. Didn't you really mean to define the instance variable? If so, leave of the first use of "Vector" on that line.

ok.. so now my next problem is that the deck is still the same.. after Shuffling the deck's arrangement is the same.. The collections for shuffle method randomly shuffles. I need to cut the deck then insert each card of the half deck alternately.

Well, nested loops for the first and second half you don't want. You want a single loop. You also don't want swap as that is moving the first card to the middle and the middle card to the front, when what you really want is to leave the first card at the front and insert the middle card into the second position, etc, etc, right? You need to rethink your algorithm.

that's what i did.. so for line 46 i start the loop at element 1 leaving element 0 on the top and swap it with element 26(the middle).. i couldn't think of anything else. if you could give me hints on what should i do, that will be a big help.

Using "swap" makes the card trade places with the one your swapping with, which, obviously, does not make the former second card the third card, which you also need to do, of course. Swap is not what you want to use. The easiest way is to create a new vector and simply add the elements to that in the order in which they should be added, then replace the original list with this new one.

I don't really quite get it.. so I will make a new vector but how am I suppose to arrange them in the order I want?

index 0, index 26, index 1, index 27, index 2, index 28, etc, etc, etc,. Do you notice a pattern there? I.E. "+ 26"? Write a loop and use index and index + 26.

ok.. Thanks! I got it now. I will try to write the code now.. Thanks!

I have a question again. After the dealing the cards to each player (there are 4 players), you have to compare the players' card at the top of their deck and determine which has the highest value of card. After comparing the all 4 cards will be at the bottom of the winner's deck. This will continue until only one player has all cards.

Here's my code

public static boolean test(){ // to test if only one player has all the cards
 	int a = player1.size();
	int b = player2.size();
	int c = player3.size();
	int d = player4.size();

	if (((a==52) && (b==0) && (c==0) && (d==0)) || ((a==0) && (b==52) && (c==0) && (d==0)) || ((a==0) && (b==0) && (c==52) &&(d==0)) || ((a==0) && (b==0) && (c==0) && (d==52)))
		{
		}	
		return true;
}
	
public static void cardPlay(){ 



	Vector v5 = new Vector();
	v5.trimToSize();

	do{	// loop till only one player has all cards.
			 
			v5.add(player1.firstElement());
			v5.add(player2.firstElement());
			v5.add(player3.firstElement());
			v5.add(player4.firstElement());
	
			//code to compare each card where w is used to determine which player has the highest card

	if (w == 1)
		{
		player1.addAll(v5);
		v5.clear();
		player1.trimToSize();
		
		}
	if (w == 2)
		{
		player2.addAll(v5);
		v5.clear();
		player2.trimToSize();
		
		}
	if (w == 3){
		player3.addAll(v5);
		v5.clear();
		player3.trimToSize();
		
		}
	if (w == 4)
		{
		player4.addAll(v5);
		v5.clear();
		player4.trimToSize();
		
		}
		player1.removeElementAt(0);
		player2.removeElementAt(0);
		player3.removeElementAt(0);
		player4.removeElementAt(0);

		
	if ((player1.size()==0) || (player2.size()==0)|| (player3.size()==0)|| (player4.size()==0))
			 {
			 		continue;
			 }	

	}
		while (test()== true);

I've made a loop until only one player has all cards. The problem is that after 1 player has zero number of cards (empty vector), The loop would stop and a NoSuchElementException error occurs. What should i do?

It is because, of course, the lines like this

player1.removeElementAt(0);

where you are attempting to reference a specific element without bothering to check whether an element exists at that index. Add an if statement to check the size of the vector before each of statements i.e.

if (vec.size() > 0) vec.removeElementAt(0);

Edit: P.S. that "trimToSize" is a rather costly method that is not necessary in this context.

Thank you so much! I'll will try it.

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.