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.

Results 1 to 15 of 15

Thread: stack overflow error

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    25
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default stack overflow error

    Hi,
    I keep getting a static overflow error, but I'm puzzled about how to fix it.

       public static Rank[] createRankArray(){
                      Rank[] rankArray= new Rank[13];
                      for(int i=0; i<rankArray.length; i++){
                          rankArray[i]= new Rank(i);
                      }
                  return rankArray;
                  }
                  Rank[] rankArray = createRankArray();

    error code
    run:
    11 ("11" is a value from earlier in the program that was supposed to print and is working fine)
    Exception in thread "main" java.lang.StackOverflowError
    at prog2.Rank.<init>(Prog2.java:101)
    at prog2.Rank.createRankArray(Prog2.java:112)
    at prog2.Rank.<init>(Prog2.java:117)
    (then it repeats the last two lines for what must be several hundred times or more)

    Java Result: 1
    BUILD SUCCESSFUL (total time: 1 second)
    Last edited by Goldfinch; February 1st, 2012 at 10:33 PM.


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: stack overflow error

    public static Rank[] createRankArray(){
        Rank[] rankArray= new Rank[13];
        for(int i=0; i<rankArray.length; i++) {
                // The createRankArray() method creates 13 new Rank instances...
            rankArray[i]= new Rank(i);
        }
        return rankArray;
    }
        // ... but each Rank instance has an array which calls createRankArray()
    Rank[] rankArray = createRankArray();

    Whatever you are trying to do, don't do it this way.

    When you create an instance of Rank the createRankArray() method will be called to populate the array. This method will try and create 13 more Rank instances, calling createRankArray() 13 times. The process will never end.

  3. #3
    Junior Member
    Join Date
    Jan 2012
    Posts
    25
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: stack overflow error

    that reminds me, I did forget to explain my objective, this is just the relevant code from a larger program and I guess I didn't include the comment line. Here is an update of the code to reflect the intention. Problem as you said is that I've created an infinite loop. I can include the entire program if that would help, I just didn't so far, because I haven't figured out how much how code is acceptable to include and at what point its just too much.
    // Item 7: a private static array with 13 elements of type Rank and initialize it with Rank objects corresponding to each of the 13 indices. Create array of objects section 8.11
                  public static Rank[] createRankArray(){
                      Rank[] rankArray= new Rank[13];
                      for(int i=0; i<rankArray.length; i++){
                          rankArray[i]= new Rank(i);
                      }
                  return rankArray;
                  }
                  Rank[] rankArray = createRankArray();
    Hope this clears it up.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: stack overflow error

    What is the definition of the Rank class? Does its constructor call any methods?
    It can NOT call the createRankArray method because that will be an infinite loop.

  5. #5
    Junior Member
    Join Date
    Jan 2012
    Posts
    25
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: stack overflow error

    Well here's the whole class:
    class Rank{
            public Rank(){//initializes new instance
     
            }
            // Item 1: a private static array of Strings and initialize it to include the names of each rank ("Ace","Two",....."King")
                  private static String[] rankNames={"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};
            // Item 2: a private static array of Strings and initialize it to include the abbreviated rank name for each rank ("A","2","3",...,"Q","K").
                  private static String[] rankNameAbbrev={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
            // Item 3: a private instance variable of type int that holds a value from 0-12 representing one of the 13 ranks
                  private static int rankIndex=0;
            // Item 4: a public constructor with one integer parameter that is used to initialize the instance variable
                  public Rank(int enterRankIndex){ rankIndex=enterRankIndex; }
            // Item 5: a public getter that uses the instance variable to return the rank name as a String.
                  public String getName(int rankIndex)
                  {return rankNames[rankIndex]; }
            // Item 6: a public getter that uses the instance variable to return the abbreviated rank name as a String
                  public String getAbbrev(int rankIndex)
                  {return rankNameAbbrev[rankIndex]; }
            // Item 7: a private static array with 13 elements of type Rank and initialize it with Rank objects corresponding to each of the 13 indices. Create array of objects section 8.11
                  public static Rank[] createRankArray(){
                      Rank[] rankArray= new Rank[13];
                      for(int i=0; i<rankArray.length; i++){
                          rankArray[i]= new Rank(i);
                      }
                  return rankArray;
                  }
                  Rank[] rankArray = createRankArray();
     
            // Item 8: a public static getter that takes a single integer as a parameter and returns the corresponding Rank object from the static array
            public static Rank getRank(Rank[] rankArray){
                Rank outputRank = rankArray[rankIndex];
                return outputRank;
            }
            // Item 9: List of Public Static Final Int variables representing the ranks
            public static final int ACE=0;
            public static final int TWO=1;
            public static final int THREE=2;
            public static final int FOUR=3;
            public static final int FIVE=4;
            public static final int SIX=5;
            public static final int SEVEN=6;
            public static final int EIGHT=7;
            public static final int NINE=8;
            public static final int TEN=9;
            public static final int JACK=10;
            public static final int QUEEN=11;
            public static final int KING=12;
     
        } // end Rank Class

    The point of the class is to be able to call instance variables in another class to get the name values for different "cards" that are held in memory. So that's why I try to create 13 objects (which as it happens is currently an infinite loop, but I've become lost about how to correct).

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: stack overflow error

    The call to createRankArray appears to be called every time a Rank object is created.
    To show this, add a println to the Rank class's constructor and to the createRankArray method.
    The output from these two printlns should show you how one is calling the other in an infinite way.

  7. #7
    Junior Member
    Join Date
    Jan 2012
    Posts
    25
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: stack overflow error

    I tried that out, and changed the code to something simpler:
      Rank[] rankArray = new Rank[13];
           for(int i=0; i<rankArray.length; i++){
           rankArray[i]= new Rank(i);
           System.out.println("create Rank marker"); }

    It resulted in a different kind of error.
    Exception in thread "main" java.lang.ClassFormatError: Duplicate field name&signature in class file prog2/Rank
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader. java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java :616)
    at java.security.SecureClassLoader.defineClass(Secure ClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader .java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader. java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java: 197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.j ava:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:3 07)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launche r.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:2 48)
    at prog2.Card.<init>(Prog2.java:49)
    at prog2.Prog2.main(Prog2.java:17)
    Last edited by Goldfinch; February 2nd, 2012 at 12:20 PM.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: stack overflow error

    at prog2.Card.<init>(Prog2.java:49)
    What is the code doing at line 49?

    java.lang.ClassFormatError: Duplicate field name&signature in class file prog2/Rank
    I've never seen this error. How are you compiling the class files?
    Last edited by Norm; February 2nd, 2012 at 12:25 PM.

  9. #9
    Junior Member
    Join Date
    Dec 2011
    Posts
    1
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: stack overflow error

    I copied the code and take "Rank[] RankArray = createRankArray();" into "public static void main(String args[])" and it's OK

  10. The Following User Says Thank You to ducbinh136 For This Useful Post:

    Goldfinch (February 2nd, 2012)

  11. #10
    Junior Member
    Join Date
    Jan 2012
    Posts
    25
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: stack overflow error

    I didn't want to dump the whole thing on anyone because I thought It would be better if I posted more manageable pieces, but I'm including the entire file here just in case it helps. Unfortunately, the java code format does not include line numbers. Line 49 is in an earlier class called Card and is a object creator that calls an instance of the Rank class. The line reads "Rank instanceR = new Rank();" If this vBulletin installation allows line numbers I'd be glad to add that if I can find out how and that helps.
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package prog2;
     
    /**
     *
     * @author ???
     */
    public class Prog2 {
        /**
         * @param args the command line arguments
         */
        public static void main(String [] args){
        System.out.println(Rank.QUEEN);
        Card card = new Card(Rank.QUEEN, Suit.SPADES);
        System.out.println(card); 
        //System.out.println(card.toStringShort()); 
        System.out.println("_____________________________"); 
       /* Deck deck = new Deck(); 
        deck.shuffle(); 
        for (int i = 0; i < 50; ++i) {
            System.out.println(deck.dealCard());
    }
        System.out.println(deck); //prints the remaining cards
        System.out.println("_____________________________");
        Shoe shoe = new Shoe(4);
        shoe.shuffle();  
        for (int i = 0; i < 50; ++i) {
            System.out.println(shoe.dealCard());
        } 
     
    System.out.println("_____________________________"); */
    }
    }
        class Card{ //outputs info for a single instance of a card
           public String singleRank;
           public String singleSuit;
           public String Card(){ 
        String test="of"; 
        return test;
      }
    public Card(){}
         // Item 1: a two arg constructor that passes in a rank and suit which will initialize the card.   
     
           //Item 2: a two arg constructor that takes two integer parameter, one representing a rank (from 0-12) and one representing a suit (from 0-3). Use these two variables to initialize the Rank and Suit instance variables.  
    public Card(int x, int y){
    Rank instanceR = new Rank();
    singleRank= instanceR.getName(x);
    Suit instanceS = new Suit();
    singleSuit= instanceS.getName(y);
        }
        //Item 3: getter methods for the Card class that return Rank and Suit.
     
        //Item 4: a toString() method, which will return the value of the card as follows: Rank of Suit such as Two of Diamonds.
        @Override
     public String toString () {
       return "This is the toString() method in the Card Class";
    }
        //Item 5: an equals method that will return true if both cards have the same rank and suit.
     
        //Item 6: a toStringShort() method which will return the value of the card as follows: abbreviated Rank (no space) abbreviated Suit such as 2D. 
     
        } // end Card class
     
     
        class Deck{ //simulates a deck of cards
           //Item 1: a no arg constructor that stores a complete set of cards (13 cards in each suit).  Hold the cards in an array of Card. 
     
           //Item 2: a method called shuffle, that will shuffle the 52 cards in the deck. Use java.util.Random to select your random numbers. 
     
           //Item 3: a method called dealCard, that returns the next card in the deck.
     
           //Item 4: a method called getCardsRemaining(), which returns the number of remaining cards in the deck that have not been played.
     
           //Item 5: a toString method, that will return a string with the remaining cards in the deck. Note toString() prints the abbreviated version of the card. Example: AD QS 4D 9H....
     
        }
     
     
        class Shoe{ //simulates storage of 2 to 8 decks of cards
           // Create a no arg constructor that stores one deck of cards in the shoe. 
     
    //o Create a one arg constructor that takes in an integer that states the number of decks in the shoe. 
     
            //o Create a method called shuffle, that shuffles all the decks in the shoe. 
     
            //o Create a method called dealCard, that returns the next card in the shoe. 
     
            //o Create a method called getCardsRemaining(), which returns the number of remaining cards in the shoe that have not been played. 
     
        }
     
     
     
        class Rank{
            public Rank(){//initializes new instance
     
            }
            // Item 1: a private static array of Strings and initialize it to include the names of each rank ("Ace","Two",....."King")
                  private static String[] rankNames={"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};
            // Item 2: a private static array of Strings and initialize it to include the abbreviated rank name for each rank ("A","2","3",...,"Q","K").
                  private static String[] rankNameAbbrev={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
            // Item 3: a private instance variable of type int that holds a value from 0-12 representing one of the 13 ranks
                  private static int rankIndex=0;
            // Item 4: a public constructor with one integer parameter that is used to initialize the instance variable
                  public Rank(int enterRankIndex){ rankIndex=enterRankIndex; System.out.println("Rank marker"); }
            // Item 5: a public getter that uses the instance variable to return the rank name as a String.
                  public String getName(int rankIndex)
                  {return rankNames[rankIndex]; }
            // Item 6: a public getter that uses the instance variable to return the abbreviated rank name as a String
                  public String getAbbrev(int rankIndex)
                  {return rankNameAbbrev[rankIndex]; }
            // Item 7: a private static array with 13 elements of type Rank and initialize it with Rank objects corresponding to each of the 13 indices. Create array of objects section 8.11
                  Rank[] rankArray = new Rank[13];
                      for(int i=0; i<rankArray.length; i++){
                          rankArray[i]= new Rank(i);
                          System.out.println("create Rank marker"); }
            // Item 8: a public static getter that takes a single integer as a parameter and returns the corresponding Rank object from the static array
            public static Rank getRank(Rank[] rankArray){
                Rank outputRank = rankArray[rankIndex];
                return outputRank;
            }
            // Item 9: List of Public Static Final Int variables representing the ranks
            public static final int ACE=0;
            public static final int TWO=1;
            public static final int THREE=2;
            public static final int FOUR=3;
            public static final int FIVE=4;
            public static final int SIX=5;
            public static final int SEVEN=6;
            public static final int EIGHT=7;
            public static final int NINE=8;
            public static final int TEN=9;
            public static final int JACK=10;
            public static final int QUEEN=11;
            public static final int KING=12;
     
        } // end Rank Class
     
     
     
     
     
        class Suit{
             public Suit(){//initializes new instance
     
            }
                   // Item 1: a private static array of Strings and initialize it to include the names of the suits ("Hearts",...)
                  private static String[] suitNames={"Hearts","Spades","Diamonds","Clubs"};
            // Item 2: a private static array of Strings and initialize it to include the abbreviated rank name for each suit ("H","S","D","C").
                  private static String[] suitNameAbbrev={"H","S","D","C"};
            // Item 3: a private instance variable of type int that holds a value from 0-3 representing one of the 4 suits
                  private static int suitIndex=0;
            // Item 4: a public constructor with one integer parameter that is used to initialize the instance variable
                  public Suit(int enterSuitIndex){ suitIndex=enterSuitIndex; }
            // Item 5: a public getter that uses the instance variable to return the suit name as a String.
                  public String getName(int suitIndex)
                  {return suitNames[suitIndex]; }
            // Item 6: a public getter that uses the instance variable to return the abbreviated suit name as a String
                  public String getAbbrev(int suitIndex)
                  {return suitNameAbbrev[suitIndex]; }
            // Item 7: a private static array with 4 elements of type Suit and initialize it with Suit objects corresponding to each of the 4 indices. Create array of objects section 8.11
                  Suit[] suitArray = createSuitArray();
                  public static Suit[] createSuitArray(){
                      Suit[] suitArray= new Suit[4];
                      for(int i=0; i<suitArray.length; i++){
                          suitArray[i]= new Suit(i);
                      }
                  return suitArray;
                  }
            // Item 8: a public static getter that takes a single integer as a parameter and returns the corresponding Suit object from the static array
            public static Suit getSuit(Suit[] suitArray){
                Suit outputSuit = suitArray[suitIndex];
                return outputSuit;
            }
            // Item 9: List of Public Static Final Int variables representing the suits
     
            public static final int SPADES = 1;
            public static final int HEARTS = 0;
            public static final int CLUBS = 3;
            public static final int DIAMONDS = 2;
        } // end suit class

  12. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: stack overflow error

    Your posted code does not compile without errors.
    How can you execute this code when it has compiler errors?

  13. #12
    Junior Member
    Join Date
    Jan 2012
    Posts
    25
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: stack overflow error

    I'm using Netbeans 7.1, it allows me to run the program until it breaks. It looks like Netbeans doesn't think there are any compile errors, just runtime errors. The program seems to execute the first println statement without any problem, then crashes when it tries to run the Card card= new Card(Rank.QUEEN,Suit.SPADES); statement, even though there are no compile errors.

    That's the statement that uses a constructor in card which relies on the Rank class (and the suit class, but the operation is almost identical, so if I fix the rank class the same solution should be easily applied to the suit class as well)
    Last edited by Goldfinch; February 2nd, 2012 at 01:19 PM.

  14. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: stack overflow error

    I use a compiler that tells me the errors before I try to execute code that won't execute.
    Your code will not compile and therefore can't be executed outside of your IDE.

  15. #14
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: stack overflow error

    // Item 7: a private static array with 13 elements of type Rank and initialize it
    Note that the rank array is supposed to be static. Think about why this should make a difference as far as the infinite loop goes.

  16. The Following User Says Thank You to pbrockway2 For This Useful Post:

    Goldfinch (February 2nd, 2012)

  17. #15
    Junior Member
    Join Date
    Jan 2012
    Posts
    25
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by ducbinh136 View Post
    I copied the code and take "Rank[] RankArray = createRankArray();" into "public static void main(String args[])" and it's OK
    As it happened I tried putting the revised code in a method and it worked.

Similar Threads

  1. stack project-runtime error
    By makonikor in forum What's Wrong With My Code?
    Replies: 16
    Last Post: July 31st, 2011, 02:16 PM
  2. stack
    By ridg18 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 22nd, 2011, 12:45 PM
  3. Stack
    By AmyH in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 7th, 2010, 04:04 PM
  4. Error of "cannot access InToPost" in 3 and 5 code
    By jaysoncutie in forum What's Wrong With My Code?
    Replies: 2
    Last Post: August 25th, 2009, 09:12 AM
  5. Replies: 0
    Last Post: October 14th, 2008, 06:40 PM