Can't shuffle

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anjkris07
    New Member
    • Jun 2010
    • 1

    #1

    Can't shuffle

    I've been studying java for a week now. I have a project that needed to display a deck of cards and shuffle them alternately (like cutting the deck then insert each card). Then deal it, much like the war game of cards. I'm just still on the shuffle stage but the the deck remains the same even after shuffling. I think my codes got problem with the swapping part. I try to think of another way to shuffle(not randomly) but nothing came up. So please HELP
    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
    		  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();	
    	}
    }
    !
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    The for loops are to blame:
    for (int j=26;j<(deck.si ze())/2;j+=2)

    if deck.size() = 26, then j >= 26 from the start -> the for loop never runs.

    Comment

    Working...