Stck-overflow(recursion)

Hi, am vikranth, joied just now.
I'm getting "stack-overflow-error" whenever I use recursion, for example, to solve towers of hanoi problem.
Please tell me how can I get along with it?

Thank you friends..for clearing my doubt.
The program is working;
but println statements are showing errors, in the following code.
// method to move N stones from "from" to "to",
Hanoi.java
// eventually using temp as a temporary place:
public class Hanoi
public static void main(String[] args)
Recur r = new Recur();
r.move(3,1,2,3);
class Recur
public void move( int N,int from,int to,int temp) // N must be > 0
if(N > 0)
move(N-1, from, temp, to);
println("from "+from+" to "+temp);
//moveOne(A, B); // move 1 element from A to B
move(N-1, temp, to, from);
println("from "+temp+" to "+to);
May I know why?

Similar Messages

  • Code works when I step through it, not when run real-time though.

    Hi,
    I have a bit of code, a trivial problem in fact, that has completely defeated me.
    private int recFibonacci(int N, long starTime) {
            long totalTime = System.currentTimeMillis() - starTime;
            if(N <= 0) return -3;  //negatives not allowed
            try {
                if (N < 2) {
                    return N;
                } else {
                    if (totalTime <= 1500) { //if it takes longer than 15 seconds, end.
                        N = recFibonacci(N - 2, starTime) + recFibonacci(N - 1, starTime);
                    } else {
                        return -1;//return if taking too long
            } catch (StackOverflowError ex) {
                return -2;//return if overflow
            return N;
    //This is the user accessible function for the recursive fibonacci method.
    //It calls the private fibonacci function and passes it a startTime value.
    //This is so that the startTime is only set at the user's call, not each time the
    //function recurses.
        public int recFibonacci(int N) {
            setTime();
            int retN = this.recFibonacci(N, getStartTime());
            if (retN == -1) {
                System.out.println("Calculation is is taking too long, try a non-recursive solution.");
                return -1;
            if (retN == -2) {
                System.out.println("Stack overflow, recursed too deeply.  Try a non-recursive solution, or a smaller number.");
                return -2;
            if (retN == -3){
                System.out.println("Fibonacci sequence is undefined for negative numbers.");
                return -3;
            return retN;
        }From the driver I call the single argument method.
    When I debug and step through the code it runs perfectly. If the number is large enough to take a little while to execute,i get the appropriate error message. Also, if the number causes a stack overflow, I get that message as well.
    When I run the code (realtime not stepping) I always get a strange return value if N is too large. Its always a different value, and I never receive the error code. I am at a complete loss to explain this discrepency.
    Any ideas?

    Seems to me your problem could be the same as this poster's:
    [Problem With Recursion|http://forum.java.sun.com/thread.jspa?threadID=5270481]
    db

  • Recursive selection sort stack overflow

    hi, first time posting here.
    i have to write a java method that implements a selection sort. This method must be recursive. ok not a problem. i have come up with this so far
        public int findMin(int index) {
            int min = index - 1;
            if (index < num.length - 1) min = findMin(index + 1);
            if (num[index] < num[min]) min = index;
            return min;
        public void selectionSort(int left) {
            if (left < num.length - 1) {
                swap(left, findMin(left));
                selectionSort(left + 1);
        public void swap(int index1, int index2) {
            int temp = num[index1];
            num[index1] = num[index2];
            num[index2] = temp;
        }which works fine until i toss in a lot of values into the array. this creates a stack overflow, and ive been told that i need to use the divide and conquer method of resolving this issue. I guess this means to split the array up and sort each half seperatly, again and agin, or so im told.
    My question is how do i go about doing this, i am at a loss. Any help at all would be great.
    thank you
    lance

    i get this when i push the array passed about 5500 in sizeI got no problem. Post a small demo code that is generally compilable, runnable and could reproduce your problem. See: http://homepage1.nifty.com/algafield/sscce.html and http://www.yoda.arachsys.com/java/newsgroups.html
    It is silly to implement selection sort with recursion, double-silly if you use double-recursion as your current code.
    /* silly but no OOME when used against 5500 element array */
    import java.util.*;
    public class RecursiveSelectionSort{
      static int[] num;
      public static int findMin(int index) {
        int min = index; // your code had a bug here
        if (index < num.length - 1){
          min = findMin(index + 1);
        if (num[index] < num[min]){
          min = index;
        return min;
      public static void selectionSort(int left) {
        if (left < num.length - 1) {
          swap(left, findMin(left));
          selectionSort(left + 1);
      public static void swap(int index1, int index2) {
        int temp = num[index1];
        num[index1] = num[index2];
        num[index2] = temp;
      public static void main(String[] args){
        Random rand = new Random();
        int n = 10;
        if (args.length > 0){
          n = Integer.parseInt(args[0]);
        num = new int[n];
        for (int i = 0; i < num.length; ++i){
          num[i] = rand.nextInt(10000);
        selectionSort(0);
        for (int in : num){
          System.out.print(in + " ");
        System.out.println();
    }

  • Recursive function definition results in stack overflow

    I am writing a library script to handle some basic calculations with complex numbers which includes a function, powerN(), that raises (or is supposed to raise) a complex number to the Nth power. The function compiles but gives a stack overflow error when called. The language guide has an example (p. 286 in PDF version- recursive subroutines section) of a recursive definition of a function which gives the factorial of a number, and my powerN function seems to be analogous. Can anyone shed some light on whatever the problem is? Relevant code examples are below. Thanks for any insights.
    -----Apple recursive subroutine for factorials------
    on factorial(x)
    if x > 0 then
    return x * (factorial(x - 1))
    else
    return 1
    end if
    end factorial
    -----End Apple recursive subroutine for factorials------
    -----My script with problematic powerN() function------
    --Complex numbers a+b(i), x+y(i) represented by {a,b}, {x,y}
    on multiply({a, b}, {x, y})
    return {(a * x + b * y), (b * x + a * y)}
    end multiply
    --above multiply function works
    on powerN({a, b}, N)
    return multiply({a, b}, powerN({a, b}, N - 1))
    end powerN
    --above powerN function gives stack overflow error
    -----End my script with problematic powerN() function------

    the problem is that your recursion has no end case, thus causing a stack overflow
    you should add a test as follows :
    on powerN({a, b}, N)
    if N>0 then
    return multiply({a, b}, powerN({a, b}, N - 1))
    else
    return 1
    end if
    end powerN
    by the way, shouldn't your complex multiplication look like :
    on multiply({a, b}, {x, y})
    return {(a * x - b * y), (b * x + a * y)}
    end multiply

  • Infinite recursion - base case ignored and stack overflowed

    Hi, I've been having this logic error for 2 days, and I cannot fix it. Right now, I can barely see anything because I was looking at computer screen for 10 hours. The code I'm writing is a program that allows the user to play a list of MP3 files in a folder. Among commands we have to make, we have to sort the list according to authors, dates, and titles as desired by the user. This specific problem I'm having is from the sorting method. We have to use quick sort, and through the help of textbook and online, I was able to write the code as follows. The problem is, I'm having an infinite recursion. The base case I wrote and if else statement are completely ignored and the method keeps calling itself. Perhaps, return statement is not how you are supposed to end a recurssive method? I have no idea. Any help will be appreciated. Thank you in advance.
    public void sort (Comparator<MP3File> comp) {
              System.out.println("first: " + first  + "last: " + last);
              quickSort(first, last, comp);
              System.out.println("done");
              return;
         public void quickSort (int left, int right, Comparator<MP3File> comp) {
              int leftBound= left;
              int rightBound= right;
              System.out.println("before sorting: left - " + left + " right - " + right);
              if (left>=right) {
                   return;
               if ( ( left < 0 ) || ( left >= listOfMP3.length ) ||
                         ( right < 0 ) || ( right >= listOfMP3.length ) ) {
                       throw new IndexOutOfBoundsException();
               if (right-left>=1) {
                    System.out.println("difference between right and left: " + (right-left));
                    MP3File pivot = listOfMP3[left];
                    while (rightBound>leftBound)
                         while (comp.compare(listOfMP3[leftBound], pivot)<= 0 && leftBound<=right &&rightBound>leftBound) {
                              leftBound++;
                              System.out.println("leftBound " + leftBound);
                         while (comp.compare(listOfMP3[rightBound], pivot)>0 && rightBound>=left &&rightBound>=leftBound) {
                              rightBound--;
                              System.out.println("rightBound " + rightBound);
                         if (rightBound>leftBound) {
                              swap (leftBound,rightBound);
                        swap(left, rightBound);
                        System.out.println("swapped");
                        System.out.println("calling left sorting");
                        quickSort(left, rightBound-1, comp);
                        System.out.println("calling right sorting");
                        quickSort(rightBound+1, right, comp);
               else {
                    System.out.println("wtf");
                    return;
               System.out.println("error");
               return;
         public void swap(int index1, int index2) {
              MP3File temp = listOfMP3[index1];
              listOfMP3[index1] = listOfMP3[index2];
              listOfMP3[index2] = temp;
         }

    naranja wrote:
    Enlighten me further please? How do you use sort method using collections?[http://www.google.com/search?q=java+sort+tutorial]

  • #2094: Event dispatch recursion overflow

    Hello,
    I can't seem to solve this error. Any help would be appreciated.
    Joseph

    Thanks!
    I eliminated the error!
    Joseph

  • Recursion too deep; the stack overflowed.

    All the solutions deal with permissions inside the jrun
    folder, however my server setup does not have a jrun folder. So how
    do I fix this problem?

    I think you're looking for wsconfig folder... Try
    cf_root/runtime/lib/wsconfig

  • SAP paging overflow when storing data in the ABAP/4 memory.

    I am trying to create a data source in  BI7.0 in the Datawarehousing Workbench. But along the process when i need to select a view i get an error detailed in the following error file extract: Please go through and assist.
    untime Errors         MEMORY_NO_MORE_PAGING
    Date and Time          06.06.2009 14:21:35
    Short text
    SAP paging overflow when storing data in the ABAP/4 memory.
    What happened?
    The current program requested storage space from the SAP paging area,
    but this request could not be fulfilled.
    of this area in the SAP system profile.
    What can you do?
    Note which actions and input led to the error.
    For further help in handling the problem, contact your SAP administrator
    You can use the ABAP dump analysis transaction ST22 to view and manage
    termination messages, in particular for long term reference.
    Error analysis
    The ABAP/4 runtime system and the ABAP/4 compiler use a common
    interface to store different types of data in different parts of
    the SAP paging area. This data includes the
    ABAP/4 memory (EXPORT TO MEMORY), the SUBMIT REPORT parameters,
    CALL DIALOG and CALL TRANSACTION USING, as well as internally defined
    macros (specified with DEFINE).
    To store further data in the SAP paging area, you attempted to
    allocate a new SAP paging block, but no more blocks were
    available.
    When the SAP paging overflow occurred, the ABAP/4 memory contained
    entries for 20 of different IDs.
    Please note:
    To facilitate error handling, the ABAP/4 memory was
    deleted.
    How to correct the error
    The amount of storage space (in bytes) filled at termination time was:
    Roll area...................... 8176
    Extended memory (EM)........... 13587912
    Assigned memory (HEAP)......... 0
    Short area..................... " "
    Paging area.................... 40960
    Maximum address space.......... " "
    By calling Transaction SM04 and choosing 'Goto' -> 'Block list',
    you can display an overview of the current roll and paging memory
    levels resulting from active users and their transactions. Try to
    decide from this whether another program requires a lot of memory
    space (perhaps too much).
    The system log contains more detailed information about the
    termination. Check for any unwanted recursion.
    Determine whether the error also occurs with small volumes of
    data. Check the profile (parameter "rdisp/PG_MAXFS", see
    Installation Guidelines).
    Is the disk or the file system that contains the paging file
    full to the extent that it cannot be increased, although it has
    not yet reached the size defined in the profile? Is the
    operating system configured to accommodate files of such a
    size?
    The ABAP processor stores different types of data in the SAP
    paging area. These include:
    (1) Data clusters (EXPORT ... TO MEMORY ...)
    (2) Parameters for calling programs (SUBMIT REPORT ...),
    Dialog modules (CALL DIALOG ...) and transactions
    (CALL TRANSACTION USING ...)
    (3) Internally defined program macros (DEFINE ...)
    Accordingly, you should check the relevant statements in a program
    that results in an overflow of the SAP paging area.
    It is critical when many internal tables, possibly with
    different IDs, are written to memory (EXPORT).
    If the error occures in a non-modified SAP program, you may be able to
    find an interim solution in an SAP Note.
    If you have access to SAP Notes, carry out a search with the following
    keywords:
    "MEMORY_NO_MORE_PAGING" " "
    "SAPLWDTM" or "LWDTMU20"
    "TABC_ACTIVATE_AND_UPDATE"
    If you cannot solve the problem yourself and want to send an error
    notification to SAP, include the following information:
    1. The description of the current problem (short dump)
    To save the description, choose "System->List->Save->Local File
    (Unconverted)".
    2. Corresponding system log
    Display the system log by calling transaction SM21.
    Restrict the time interval to 10 minutes before and five minutes
    after the short dump. Then choose "System->List->Save->Local File
    (Unconverted)".
    3. If the problem occurs in a problem of your own or a modified SAP
    program: The source code of the program
    In the editor, choose "Utilities->More
    Utilities->Upload/Download->Download".
    4. Details about the conditions under which the error occurred or which
    actions and input led to the error.

    Hi Huggins,
    Maintenance of the Paging File is owned by your basis team.
    They should increase this in order for your transaction to process successfully.
    Just for your reference, in case the OS used is windows server 2003, paging file value can be checked through;
    Right click in the My Computer&gt;properties.
    Then go to Advance tab;
    Then there should be a performance section, click the settings
    Then Advance tab again. The paging file can be seen from there.
    (and can be adjusted from there also)
    The value of the paging file in general will be dependent with the available RAM from the hardware.
    Hope this helps. Thanks a lot.
    - Jeff

  • CSS Style Sheet Link Recursive Error?

    I am trying to link a css style sheet to a new root file. When I try to link the css sheet I get an error - A recursive style import was found while trying to add Check Magazine.css. Please resolve this error by editing the file in an external text editor and try again.
    What does this mean?  I looked up recursive style everywhere and there is no explanation.  I don't know how to fix.  The answer I found on these forums mentioned an @import statement error but I dont even have any @import statemensts in my style sheet this style sheet is part of the Getting Started tutorial on this website.
    @charset "utf-8";
    #container{
    width: 968px;
    background: #FFFFFF;
    margin: 0 auto;
    padding-left: 10px;
    padding-right: 10px;
    overflow: hidden;
    This is my code, can you help?

    This is my index.html code, I am so lost as to what to do to get rid of this stupid error.  My style sheet is not linked so of course it is useless and I have to code on both documents since the code doesnt show up automatically on the Style sheet when I add something to the index page
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Check Magazine</title>
    <style type="text/css">
    <!--
    #banner {
    background-image: url(images/banner.gif);
    height: 100px;
    width: 968px;
    #main_image {
    background-image: url(images/main.jpg);
    height: 376px;
    width: 968px;
    #left_column {
    float: left;
    width: 316px;
    #column_container {
    float: left;
    width: 652px;
    #right_column {
    float: right;
    width: 316px;
    #center_column {
    width: 316px;
    margin-left: 10px;
    -->
    </style>
    </head>
    <body>
    <div id="container">
      <div id="banner"></div>
      <div id="main_image"></div>
      <div id="left_column">Content for  id "left_column" Goes Here</div>
      <div id="column_container">
        <div id="right_column">Content for  id "right_column" Goes Here</div>
        <div id="center_column">Content for  id "center_column" Goes Here</div>
      </div>
    </div>
    </body>
    </html>

  • Problems with a recursive stack

    Hello!
    I?ve got problems with a recursive stack.
    I?ve got a stack overflow error. Here
    is my push method.
    public void push(Object o)
        StackRekursiv stack = new StackRekursiv();
        stack.top = top;
        stack.rest = rest;
        if(top==null && rest==null)
          rest = stack.rest = new StackRekursiv();
          top = stack.top = o;
        else
          push(rest.top);
          rest = stack.rest = stack;
          top = stack.top = o;
    Thank you for your help!

    [url http://forum.java.sun.com/thread.jsp?forum=31&thread=467503]Cross-post. This is not considered [url http://pjt33.f2g.net/javafaq/posting.html]good etiquette.

  • Recursively Retrieving All the Files/Directories in a Directory

    Hello,
    I want to retrieve all files in a directory, and ran into this sample code:
    www.ni.com/example/27157/en/
    This is the function that does the retrieve action:  GetFilesAndDirectories().  Its content is as follow:
    void GetFilesAndDirectories(char dir[], int* numItems, int parentItem)
    char fileName[MAX_PATHNAME_LEN], searchPath[MAX_PATHNAME_LEN];
    int error = 0;
    strcpy (searchPath, dir);
    strcat (searchPath, "\\*");
    if (!GetFirstFile (searchPath, 1, 1, 0, 0, 0, 0, fileName)) // has at least one file
    InsertListItem (panelHandle, PANEL_LISTBOX, -1, fileName, (*numItems)++);
    while (!GetNextFile (fileName))
    InsertListItem (panelHandle, PANEL_LISTBOX, -1, fileName, (*numItems)++);
    if (!GetFirstFile (searchPath, 0, 0, 0, 0, 0, 1, fileName)) // has at least one directory
    char dirNamesSaved[MAX_NUM_DIR][MAX_PATHNAME_LEN];
    int numDir = 0, i;
    strcpy (dirNamesSaved[numDir++], fileName);
    while (!GetNextFile (fileName) && numDir<MAX_NUM_DIR) // first save all the directory names
    strcpy (dirNamesSaved[numDir++], fileName);
    for (i=0; i<numDir; i++)
    char displayName[MAX_PATHNAME_LEN];
    Fmt (displayName, "%s<%s%s", fileName, " (Directory)");
    InsertListItem (panelHandle, PANEL_LISTBOX, -1, displayName, (*numItems)++);
    MakePathname (dir, dirNamesSaved[i], searchPath);
    GetFilesAndDirectories(searchPath, numItems, (*numItems)-1);
    I then modify that function into one that I can use to retrieve either files or folders, and populate a ring object with the result.  I call it Ring_Populate().  Its content is as follow:
    void Ring_Populate (int panel, int TargetRing, char TargetFolder[], int Directory_Bool, int *Iteration_Now, int Iteration_Prev)
    char FileName [260]; //standard = 260 max char. w/ null char.
    char Folder [260];
    strcpy (Folder, TargetFolder); //copy string
    strcat (Folder, "*"); //add wildcard character, * or ?
    switch (Directory_Bool)
    case 0: //file
    if (!GetFirstFile(Folder, 1, 1, 0, 0, 0, 0, FileName)) //has at least 1 file
    InsertListItem (panel, TargetRing, -1, FileName, (*Iteration_Now)++);
    while (!GetNextFile(FileName))
    InsertListItem (panel, TargetRing, -1, FileName, (*Iteration_Now)++);
    break;
    default: //folder
    if (!GetFirstFile(Folder, 0, 0, 0, 0, 0, 1, FileName)) //has at least 1 folder
    int Folder_No = 0;
    int Folder_Max = 50; //max 50 folders
    char Folder_List [50][260]; //name 260 max
    strcpy (Folder_List [Folder_No++], FileName); //copy first element then ++
    while ( (!GetNextFile(FileName)) && (Folder_No < Folder_Max) )
    strcpy (Folder_List [Folder_No++], FileName); //copy all folder names
    for (int i = 0; i < Folder_No; i++)
    char modFolder [260];
    //Fmt (modFolder, "%s<%s%s", FileName, " (DIR)");
    //InsertListItem (panel, TargetRing, -1, modFolder, (*Iteration_Now)++);
    //MakePathname (TargetFolder, Folder_List [i], Folder); //recycle
    //Ring_Populate (panel, TargetRing, TargetFolder, 1, Iteration_Now, (*Iteration_Now) - 1);
    Fmt (modFolder, "%s<%s%s", Folder_List [i], " (DIR)");
    InsertListItem (panel, TargetRing, -1, modFolder, i);
    break;
    It works fine.  However, the section that I commented out (modified from the sample code, which works) gives me stack overflow.
    //Fmt (modFolder, "%s<%s%s", FileName, " (DIR)");
    //InsertListItem (panel, TargetRing, -1, modFolder, (*Iteration_Now)++);
    //MakePathname (TargetFolder, Folder_List [i], Folder); //recycle
    //Ring_Populate (panel, TargetRing, TargetFolder, 1, Iteration_Now, (*Iteration_Now) - 1);
    This is the original code:
    char displayName[MAX_PATHNAME_LEN];
    Fmt (displayName, "%s<%s%s", fileName, " (Directory)");
    InsertListItem (panelHandle, PANEL_LISTBOX, -1, displayName, (*numItems)++);
    MakePathname (dir, dirNamesSaved[i], searchPath);
    GetFilesAndDirectories(searchPath, numItems, (*numItems)-1);
    Question:
    1. How do I get stack overflow?  My code is essentially the same.
    2. My modified code works fine retrieving the list of folders.  I do not see the need to call the function recursively.  Can anyone explain?

    Hello all,
    I can't figurate how to list all the root directories
    (C:/> , D:/>, E:/> etc.) in a system.
    I know how to recursively check the content of a
    directory and all its subdirectories when a
    predefined path is defined. However what I' d like to
    do is actually give the option to pick one of the
    root directories to start the iteration. I have been
    looking around but I can' really find anything
    helpful.
    If any of you has any idea on how to achieve the
    above objective some clarification would be really
    appreciated.
    Thanks in advance for your help!How to installing the Javax.comm package

  • Stack overflow error

    Hi..
    I have problem with this code.
       class test
           test tt=new test();   //1
           String name1;
        test() {}
        test(String i)
              name1=i;
             //tt=new test();    //2
       public static  void main(String arg[]){
                  test t1=new test("kj"); //3
    }  When I use line 2 (nstead of line 1 ) for initializing the ref variable iam not having any problem.
    But if i use as in line 1 iam getting stack overflow error..
    I thought tht calling a constructor recursivley results in a stack overflow error..
    But iam instantiating t1 with a one arg constructor (line 3) for which tt (line 1)is intialized,then where is the recursion happening..
    can any one pls clear..
    Thnx.
    mysha..

    please use [code][/code] tags around your code - makes it much easier to read.
    I think you have it - consider this code:public class StackOverflower {
        private StackOverflower so = new StackOverflower();
        public static void main(String[] args) {
            StackOverflower mySO = new StackOverflower();
    }Running this will overflow the stack since creation of an instance of StackOverflower requires creation of an instance of StackOverflower. This code though:public class NonStackOverflower {
        private NonStackOverflower nso = null;
        public NonStackOverflower() {
        public NonStackOverflower(String s) {
            this.nso = new NonStackOverflower();
        public static void main(String[] args) {
            NonStackOverflower myNSO = new NonStackOverflower();
    }Won't, since the creation of a new NonStackOverflower is not required to create a new NonStackOverflower instance.
    Did that make sense? I may have gotten confused and failed to illustrate your situation with my code...
    Good Luck
    Lee

  • Modifying existing recursive algorithm to an iterative version

    Hi,
    I find myself wanting to modify the algorithm below to an iterative version or possibly one thats tail recursive because I'm getting stack overflow errors with the input i present my program. Can someone help me break this down? I've tried several approaches, and I seem to get stuck each time, not being able to express what I want appropriately without using recursion.
            public void visitAll(HeapItem hi) {
                HeapItem refs[] = hi.getReferences();
                HeapItem item;
                int i;
                hi.visited = true;
                for (i = 0; i < refs.length; ++i) {
                    item = refs;
    if (item != null && !item.visited)
    visitAll(item);

    You should do something like this...
    public void visitAll(HeapItem hi) {
                HeapItem refs[] = hi.getReferences();
                HeapItem item;
                int i;
                if(refs.length == 0) return;
                hi.visited = true;
                for (i = 0; i < refs.length; ++i) {
                    item = refs;
    if (item != null && !item.visited)
    visitAll(item);

  • Understanding Recursion part II

    Hello;
    I went back through the chapter on recursion and realized part of my problem was not understanding what happens in the steps.
    Some calls are easy to understand like this one
    import java.util.*
    public class CountDown
    private int count;
    public static void main(String[] args)
    CountDown countDowner = new CountDown( );
    countDowner.getCount( );
    countDowner.showCountDown( );
    public void getCount( )
    System.out.println("Enter a positive number:");
    Scanner keyboard = new Scanner(System.in);
    count = keyboard.nextInt( );
    if (count <= 0)
    System.out.println("Input must be positive.");
    System.out.println("Try again.");
    getCount( );//start over
    public void showCountDown( )
    int left;
    System.out.println("Counting down:");
    for (left = count; left >= 0; left--)
    System.out.print(left + ", ");
    System.out.println("Blast Off!");
    }Here's one I'm stuck understanding ;
    This program returns ten to the power of user integer.
    import java.util.*;
    public class tenToThe
    public static void main(String[] args)
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter an integer greater than zero");
    int userNumber = keyboard.nextInt();
    double result = (double)tenToThe(userNumber);
    System.out.println("10 to the " + userNumber + " power is "
    + result);
    private static double tenToThe(int n)
    if (n==0)
    return 1;
    else
    return (tenToThe(n-1)*10);
    }So when I put in three as my user integer, the first if is not true, but it looks like the next expression is equivalent to (3-1)*10 equal 20??
    I don't see how they got to 1000.
    Last bits. Tonight I wrote an iterative method that sums an array hoping it might give me insight how to make it recursive. This works but still stumped. What would be the steps to make it recursive?
    public class iterativeSumArray
         /** iterative method returns the value of each element in array */
         public static void main(String[] args)
                   int[] a = {2,3,4,5,6,7,8,9};
                   System.out.println(iterativeSumArray.sumArray(a));
         private static int sumArray(int[] theArray)
              int sum = 0;
              for (int i=0; i< theArray.length-1; i++)
                   sum += theArray;     
              return sum;
    Thanks again for your help and patience!
    Edited by: Zarnon on Feb 28, 2008 6:41 PM
    Edited by: Zarnon on Feb 28, 2008 6:42 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    if u know how to play with stacks or if u know How internally recursion works ( ofcourse with stack) , then i dont think ther is any difficulty u face while programming with recursion . (Make your data Structure fundamental clear, first . )
    What would be the steps to make it recursive?
    public class MySumArray
         static int sum, i, length;
         /** iterative method returns the value of each element in array */
         public static void main(String[] args)
                   int[] a = {2,3,4,5,6,7,8,9};
                   System.out.println(MySumArray.sumArray(a, a.length));
         private static int sumArray(int[] theArray, int length)
              if(length != 0)
                   sum += theArray[length - 1];
                   sumArray(theArray, --length);
              return sum;
    }here i modify your code , to make it work recusively , but if u can do the same job by iterarion ( Java provide good Iterator class in java.util.*) , then dont go for recursion (it may happen u stuck in infinte recursive loop , and may stack overflow )
    Hope this help..

  • Recursive fitness

    hi!
    I am trying to rebuild my script to make a recursive fitness of textframes. With a deep nested set of anchored objects (inline and custom position)
    All works well,but when i in my loop tries to first change the current textframe and directly after that change my parent I get an errror msg saying "invalid object for this request".
    I have figured out by stepping with the debugger that when i try to change one textframe twice i breaks (because a textframe can be a parent of many textframes). i think it can have something to do with "allowOverrides" set to false.
    Any help would be very appreciated!

    Hi!
    If the anchored object is custom and you check in the "keep whitin top/bottom bounderies" box. The fit frame to content will make room for the box, but if you have to objects anchored in the same textbox, one of them inline and one of them custom, the inline object has overflow and the other not. And you make fit frame to content on that frame it will lay itself over the other anchored frame.
    So I allways uncheck this box.
    The only way I have found to solv this is by calculating the coordinates of the parent textframe so that it resize itself accoring to the custom child object.
    But then you have to loop to all textframes so that you keep track of witch textframe is a parent and witch textframe is a child and compare there lowest points.
    Is there any other way of doing this in a better way? Or could I implement the "compare" function in your example some how?
                var txtframebottom = frame.paragraphs.item(i).textFrames.item(j).geometricBounds[2];
                var parentframebottom = frame.geometricBounds[2];   
                if(parentframebottom < txtframebottom){
                    var parentframetop = frame.geometricBounds[0];   
                    var parentframeright = frame.geometricBounds[3];   
                    var parentframeleft = frame.geometricBounds[1];   
                    var oldheight = parentframebottom - parentframetop;       
                    var newheight = oldheight + txtframebottom - parentframebottom;
                    var heightprocent = 100*(newheight/oldheight);   
                    frame.geometricBounds = [0, parentframeleft, newheight, parentframeright];

Maybe you are looking for

  • How can I include podcasts in playlists and transfer them to my ipod?

    How can I transfer playlists that include podcasts to my new ipod classic? The playlist on itunes includes them, but they do not transfer to the ipod.

  • Unable to create file using java.io.File

    I have attached my code public boolean validateZip(MultipartFile file, List<String> files) throws Exception {           String fileName = file.getOriginalFilename();           File tempFile = new File("C://workspace//tempData//" + fileName);         

  • Connect Sony HDR-SR8 via USB to FCX

    I have a Sony HDR-SR8, this handycam don't support firewire but only USB: it's possible to connect this device to Final Cut Express HD? it's necessary a special cable USB to Firewire? it exists? or a Componet to firewire? Final cut don't see my handy

  • Gedit via remote X causes crash

    I have experienced some odd behavior when running ssh -X from my Solaris 9 x86 and connecting to a Redhat 8 x86 machine. If I run xclock, emacs or other non-GTK+ and non-Qt based GUI applications everything works fine. When I try to run a GTK+ based

  • Blocking the Inactive Vendor Accounts

    Hi, I am new into FI and I have a very basic question. I want to find out if there is a program that can be scheduled to run every day to find and block the inactive vendor accounts for a specific period (say inactive for last 30 or 60 days). As of n