Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 28

Thread: Splitting up array's:

  1. #1
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Splitting up array's:

    The file has a 1000 strings that look like this.

    6S 8D KS 2D TH TD 9H JD TS 3S
    KH JS 4H 5D 9D TC TD QC JD TS
    QS QD AC AD 4C 6S 2D AS 3H KC
    4C 7C 3C TD QS 9C KC AS 8D AD
    KC 7H QC 6D 8H 6S 5S AH 7S 8C
    3S AD 9H JC 6D JD AS KH 6S JH
    AD 3D TS KS 7H JH 2D JS QD AC
    9C JD 7C 6D TC 6H 6C JC 3D 3S
    QC KC 3S JC KD 2C 8D AH QS TS
    AS KD 3D JD 8H 7C 8C 5C QD 6C

    Each represents a poker hand. The issue is each line has player one and player two. I am trying to split them up so I can figure out who won.

    package pokerHandCalculator;
     
    import java.io.*;
    import java.util.ArrayList;
     
    public class PokerCalculator 
    {
    	ArrayList<String>pokerHands = new ArrayList<String>();
    	void readFile()
    	{
    		String line;
    		try
    		{
    		FileReader file = new FileReader("poker.txt");
    		BufferedReader buffer = new BufferedReader(file);
     
    		while((line=buffer.readLine()) != null)
    		{
    			pokerHands.add(line);
    		}
     
    		buffer.close();
    		}
    		catch(Exception ex)
    		{
    			System.out.println("The file was not read or not found "+ ex);
    		}
     
    	}
     
    	void print()
    	{
    		int count=0;
     
    		for(String s: pokerHands)
    		{
    			System.out.println(s);
    			count++;
    		}
    		System.out.println(count);
     
    	}
     
     
    	public static void main(String[] args) 
    	{
    		PokerCalculator poker = new PokerCalculator();
     
    		poker.readFile();
    		poker.print();
     
    	}
     
    }

    I have tried to handle it like this along with a few other unsuccessful ways:

    void separateHand()
    {
        //ArrayList<String> hands = (ArrayList<String>) pokerHands.subList(0,5);
        ArrayList<String>hands = new ArrayList<String>();
        int count=0;
        /*pokerHands has all the variables from the file in lines of ten
        strings reading like:
        QC KC 3S JC KD 2C 8D AH QS TS
        AS KD 3D JD 8H 7C 8C 5C QD 6C 
        Below should break them up into separate arrays of 5 cards
         * */
     
        for(String s : pokerHands)
        {
            count++;
            if(count % 5 == 0)
            {
                hands = new ArrayList<String>();
                hands.add(s);
            }
            else
            {
                hands.add(s);
            }
     
        }
     
        for(String list: hands)//Testing if it worked
        {
            System.out.println(list);
        }
    }

    Also posted at http://www.java-forums.org/new-java/...oker-game.html


  2. #2
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    623
    Thanks
    0
    Thanked 112 Times in 97 Posts

    Default Re: Splitting up array's:

    What exactly is the question? What do you want to do? What is not working?

  3. #3
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    Each line has a ten strings. 5 cards each so I need to break them up into player 1 and player 2.

  4. #4
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    My Mood
    Starving
    Thanks
    1
    Thanked 8 Times in 6 Posts

    Default Re: Splitting up array's:

    Couldn't you just create an array for each player, then iterate throught the main array, alternating between the player arrays and assigning them hands?

  5. #5
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    623
    Thanks
    0
    Thanked 112 Times in 97 Posts

    Default Re: Splitting up array's:

    You can simply use the split method from the String class. You split them on every space character.
    You will get a String array with each element being one card. So every 5 cards belong to a different player, you can use a simple for-each loop.

  6. #6
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    I tried that but it did not work.

    They are already split up into 1000 different string each containing two characters all seperated by a space. Each line has ten cards:
    QC KC 3S JC KD 2C 8D AH QS TS
    AS KD 3D JD 8H 7C 8C 5C QD 6C
    is an example of what the txt file look like. I am at work at the moment so I have not been able to try this out but I was think of reading until a new line char is read \n. At which point I would make a new array taking in the 10 strings from the next line. After that is complete I can use the substring method from the string class to spilt up player 1 and player 2 hands. What do you think?

  7. #7
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    623
    Thanks
    0
    Thanked 112 Times in 97 Posts

    Default Re: Splitting up array's:

    I think I dont understand what your problem is. You said "it did not work" but what exactly about that approach does not work?

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,312
    My Mood
    Mellow
    Thanks
    194
    Thanked 669 Times in 656 Posts

    Default Re: Splitting up array's:

    After that is complete I can use the substring method from the string class to spilt up player 1 and player 2 hands. What do you think?
    I think that approach is much more difficult than using the split() method as suggested by Cornix in post #5:

    If I were writing this, I would start my program with the following comments:

    // read a line of the file as a String, pokerData

    // assign each element of pokerData to a string array:

    // split the String on a space into cards
    String[] twoHands = pokerData.split( " " );

    // the first five elements of twoHands are the first player's cards,

    // the second five elments of twoHands are the second player's cards

    // send each group of five elements to the constructor of Hand class

    // compare the Hands to determine a winner

  9. #9
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    Thank you very much. I played around with this a little more and I think I got it. However I have an error, I will post the fill code below.

    package pokerHandCalculator;
     
    import java.io.*;
     
    public class PokerCalculator 
    {
    	String[] pokerData = new String[1000];
    	String[] playerOne = new String[1000];
    	String[] playerTwo = new String[1000];
     
    	String[] playerOneCard = new String[500];
    	String[] playerTwoCard = new String[500];
     
    	void readFile()
    	{
    		int index=0;
    		String line;
    		try
    		{
    		FileReader file = new FileReader("poker.txt");
    		BufferedReader buffer = new BufferedReader(file);
     
    		while((line=buffer.readLine()) != null)
    		{
    			pokerData[index++]=line;
     
    		}
     
    		buffer.close();
    		}
    		catch(Exception ex)
    		{
    			System.out.println("The file was not read or not found "+ ex);
    		}
     
    	}
     
     
    	void separateHands()
    	{
     
    		for(int i=0; i<pokerData.length;i++)
    		{
    			playerOne[i] = pokerData[i].substring(0, 14);
    			playerTwo[i] = pokerData[i].substring(15,29);
     
    			playerOneCard[i]=playerOne[i].split(" ");
    			playerTwoCard[i]=playerTwo[i].split(" ");
    		}
     
     
    	}
     
    	public static void main(String[] args) 
    	{
    		PokerCalculator poker = new PokerCalculator();
     
    		poker.readFile();
    		poker.separateHands();
     
    	}
     
    }

    Error on line 48 and 49 saying cannot convert String[] to String. But they are both array's, this confuses me.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,618
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Splitting up array's:

    Can you post the lines mentioned in the error message?

    cannot convert String[] to String
    The compiler sees a String array to the right of the =
    and a String to the left of the=

    Remember that an element of a one dim array is NOT an array.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    My Mood
    Starving
    Thanks
    1
    Thanked 8 Times in 6 Posts

    Default Re: Splitting up array's:

    arr[] refers to an array.

    arr[i] refers to the element at index i in arr[],
    so if arr[] were a String array, arr[i] would be referring to a String

  12. The Following User Says Thank You to koder632417 For This Useful Post:

    GregBrannon (June 11th, 2014)

  13. #12
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    I get what you are saying, I will try to comment the code the best I can so you can see where my head is at.

    void separateHands()
    	{
     
    		for(int i=0; i<pokerData.length;i++)
    		{
    			playerOne[i] = pokerData[i].substring(0, 14);//makes a string of 5 cards
    			playerTwo[i] = pokerData[i].substring(15,29);//makes another string of 5 cards
     
    			playerOneCard[i]=playerOne[i].split(" ");//for every space assign that string (card) to playerOneCard[i]
    			playerTwoCard[i]=playerTwo[i].split(" ");//for every space assign that string (card) to playerTwoCard[i]
     
    		}
     
    	}

    I took the [] from playerOneCard and it worked. I was able to get the first card from the last line on the file. So basically it is over writing itself which is why I wanted to make an array of strings.
    Therefore since I knew my way was not working I decided to make a ArrayList and just add playerOneCard to it and get it later. Well that didn't work either and I am confused because both sides are strings. The index of playerOneCard[i] is AH for example and the index of playerOne[i] = AH BH 7H AS 7C. Using something like below in my mind should break it up. Where am I being a dummy here because it is obvious I am.
    playerOneCard[i]=playerOne[i].split(" ");

  14. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,618
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Splitting up array's:

    Is this how the sets of 2 characters in the String are positioned?
    p1c1 p1c2 p1c3 p1c4 p1c5 p2c1 p2c2 p2c3 p2c4 p2c5
    where pxcy means player x card y
    The first 5 cards are for player 1 and the next 5 cards are for player 2
    If the 10 cards are put into an array with the split() method then two loops could get the cards for the two players:
    First loop gets first 5 cards for player 1
    next loop get second 5 cards for player 2
    If you don't understand my answer, don't ignore it, ask a question.

  15. #14
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    Everything I am doing is failing. Are you referring to a double or two separate for loops? This fun program is becoming very un-fun.

    I tried substring, split, loops, transferring betweens different arrays.

    substring worked great and I tried to use charAt(i) to break up that array string and assign each index into a different array but that gave me issues to.

  16. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,618
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Splitting up array's:

    I was using two separate for loops.

    Another way (in stead of using split) is to use the Scanner class. Pass the String with the 10 tokens to its constructor and use two for loops with the Scanner class's next() method to get 5 cards for the first player in the first loop and 5 cards for the second player in the second loop.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #16
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    623
    Thanks
    0
    Thanked 112 Times in 97 Posts

    Default Re: Splitting up array's:

    Here, look at this little example:
    	public static void main(String[] args) {
    		String input = "a1 a2 a3 b1 b2 b3";
    		String[] cards = input.split(" ");
     
    		String[] playerOneCards = new String[3];
    		String[] playerTwoCards = new String[3];
    		for (int i = 0; i < 3; i++) {
    			playerOneCards[i] = cards[i];
    		}
    		for (int i = 3; i < 6; i++) {
    			playerTwoCards[i - 3] = cards[i];
    		}
    		System.out.println("The hand of player 1 is:");
    		for (String s : playerOneCards) {
    			System.out.print(s);
    			System.out.print(", ");
    		}
    		System.out.println();
    		System.out.println("The hand of player 2 is:");
    		for (String s : playerTwoCards) {
    			System.out.print(s);
    			System.out.print(", ");
    		}
    	}
    Maybe this will help you understand what I was talking about in my previous post.

    We first split our original input after every blank. This will give us a String-array with 6 elements (in this example).
    We want to have the first 3 elements as the hand of player 1 and the next 3 elements as the hand of player 2.
    To represent the hands of both players we use additional arrays. We fill those arrays in the for-loops. Be careful with the indices, it is easy to get an ArrayIndexOutOfBoundsException if you use bad values for the beginning and end of the iteration.

  18. #17
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    Feeling really dumb right now...

    void separateHands()
    	{
     
    		String[] cards=pokerData[0].split(" ");
    		int index =0;
     
    			for(int i=0;i<5;i++)
    			{
    				playerOne[i]= cards[i];
    			}
    			for(int j=5;j<10;j++)
    			{
    				playerTwo[j-5]= cards[j];
    			}
     
     
    		for(int i=0;i<5;i++)
    		{
    			System.out.println(playerOne[i]);	//testing the output 
    		}
     
    	  }

    I did it but I can only get the first line. This method is similar to the subString method that I was using. I even tried for use a loop like

    for(int i=0;i<5;i++,index++)
    {
            cards=pokerData[index].split(" ");
    //array variables here
    }

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,618
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Splitting up array's:

    Change the separateHands() method to take the String with the 10 cards as a parameter. Then call it with each of the lines from the file as needed.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #19
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    I am still really trying over here. I sent in a string as a parameter and tried to use the split method again. The output will be posted below. I put in a test println statement to see what was going on:



    package pokerHandCalculator;
     
    import java.io.*;
    import java.util.ArrayList;
     
    public class PokerCalculator 
    {
    	String[] pokerData = new String[1000];
    	String[] playerOne = new String[1000];
    	String[] playerTwo = new String[1000];
     
    	ArrayList<String>p1 = new ArrayList<String>();
    	ArrayList<String>p2 = new ArrayList<String>();
     
    	void readFile()
    	{
    		int index=0;
    		String line;
    		try
    		{
    		FileReader file = new FileReader("poker.txt");
    		BufferedReader buffer = new BufferedReader(file);
     
    		while((line=buffer.readLine()) != null)
    		{
    			pokerData[index++]=line;
    			separateHands(line);
    		}
     
    		buffer.close();
    		}
    		catch(Exception ex)
    		{
    			System.out.println("The file was not read or not found "+ ex);
    		}	
    	}
     
    	void separateHands(String cards)
    	{
    		String[] parts = cards.split(" ");
     
    		System.out.println(cards +" printing cards");
     
    			for(int i=0;i<5;i++)
    			{	
    				playerOne[i]= parts[i];
    			}
    			for(int j=5;j<10;j++)
    			{
    				playerTwo[j-5]= parts[j];
    			}
     
    			System.out.println(playerOne[1]);
     
    	  }
     
    	public static void main(String[] args) 
    	{
    		PokerCalculator poker = new PokerCalculator();
     
    		poker.readFile();
     
    	}
     
    }

    AD 3D TS KS 7H JH 2D JS QD AC printing cards
    3D
    9C JD 7C 6D TC 6H 6C JC 3D 3S printing cards
    JD
    QC KC 3S JC KD 2C 8D AH QS TS printing cards
    KC
    AS KD 3D JD 8H 7C 8C 5C QD 6C printing cards
    KD


    These cards are at the bottom of the text file but they are index 1.

    Now looking even further at was is going on I did the following:

    void separateHands(String cards)
    	{
    		String[] parts = cards.split(" ");
     
    		//System.out.println(cards +" printing cards");
     
    		System.out.println("Player one");
    			for(int i=0;i<5;i++)
    			{	
    				playerOne[i]= parts[i];
    				System.out.println(playerOne[i]);
    			}
    			System.out.println("Player Two");
    			for(int j=5;j<10;j++)
    			{
    				playerTwo[j-5]= parts[j];
    				System.out.println(playerOne[j]);
    			}
     
    			System.out.println(playerOne[1]);
     
    	  }

    To get the following output:

    Player one
    8C
    TS
    KC
    9H
    4S
    Player Two
    null
    null
    null
    null
    null
    TS
    Player one
    5C
    AD
    5D
    AC
    9C
    Player Two
    null
    null
    null
    null
    null
    AD
    Player one
    3H
    7H
    6S
    KC
    JS
    Player Two
    null
    null
    null
    null
    null
    7H

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,618
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Splitting up array's:

    Try doing some debugging. One way is with println() statements.
    Print the value of cards that is passed to the method
    and print the value of parts from the split method: use the Arrays class's toString() method to format the array:
    System.out.println("an ID "+ java.util.Arrays.toString(theArrayName));

    How large are the arrays (playerOne and playerTwo) that are being filled inside of the loops? Use the above println() and toString() methods to print the contents of those arrays after they are filled in the loops so you can see exactly what is in each array.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #21
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    Ok so I think I solved the issue. I figured a simple ArrayList would be the most simple way to handle this. However now I keep getting an error saying the file could not be opened which is produced by my catch statement.

    How the heck is me using a different method inside my while loop stopping it from opening the file.

    import java.io.*;
    import java.lang.reflect.Array;
    import java.util.*;
     
     
    public class CountWinnerPoker 
    {
    	ArrayList<String> pokerHands = new ArrayList<String>();
    	ArrayList<String> player1 = new ArrayList<String>();
    	ArrayList<String> player2 = new ArrayList<String>();
    	String[] playerData = new String[1000];
     
    	String line;
    	String array[];
     
    	void readFile()
    	{
    		int index = 0;
    		try{
    		FileReader file = new FileReader("poker.txt");
    		BufferedReader buffer = new BufferedReader(file);
     
    		while((line=buffer.readLine()) != null)
    		{
    			splitArray(line);
     
    			//playerData[index++] = line;	
    		}
    		buffer.close();
     
    		}
    		catch(Exception ex)
    		{
    			System.out.println("Could not open the file");
    		}
     
    	}
     
    	void splitArray(String card)
    	{
    		String[] data = card.split(" ");
     
    		for(int i=0;i<card.length() / 2;i++)
    		{
    			player1.set(i,data[i]);
    		}
    		for(int j=card.length() / 2; j<card.length(); j++)
    		{
    			player2.set(j,data[j]);
    		}
    	}
     
    	void getPlayers()
    	{
    		for(int i=0;i<player1.size();i++)
    		{
    			System.out.println(player2.get(i));
    		}
     
    	}
     
    	public static void main(String[] args) 
    	{
    		CountWinnerPoker game = new CountWinnerPoker();
     
    		game.readFile();
    		game.getPlayers();
    	}
     
    }

  23. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,618
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Splitting up array's:

    I keep getting an error
    Please copy the full text of the error message and paste it here. It has important info about the error.

    Add a call to the printStackTrace() method to the catch block to get the full text of the error message and other info.

    Where are the println() statements for debugging?
    If you don't understand my answer, don't ignore it, ask a question.

  24. #23
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    623
    Thanks
    0
    Thanked 112 Times in 97 Posts

    Default Re: Splitting up array's:

    You are catching any exception in your code. Perhaps the exception has nothing to do with the file-handling but rather you made some other mistake somewhere down the line.
    Instead of just ignoring the exception completely you should print the error message in order to know what is happening:
    		try{
     			// stuff...
    		}
    		catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}

    Try again with this code and tell us the error message you are getting.

  25. #24
    Member
    Join Date
    Apr 2014
    Posts
    210
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: Splitting up array's:

    Could not open the file java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

  26. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,618
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Splitting up array's:

    Please copy the full text of the error message and paste it here. It has important info about the error.
    If you don't understand my answer, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. Help splitting into two different classes.
    By rehrnsberger in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 23rd, 2012, 10:05 AM
  2. Splitting text into several components
    By clydefrog in forum File I/O & Other I/O Streams
    Replies: 31
    Last Post: February 23rd, 2012, 11:50 AM
  3. Splitting String
    By JuLiAnc in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 17th, 2011, 09:23 AM
  4. Splitting an Array?
    By ThatGuy1234 in forum Java Theory & Questions
    Replies: 1
    Last Post: January 19th, 2011, 07:20 AM
  5. Splitting File into Array
    By Scottj996 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: March 3rd, 2010, 10:48 AM