Search code examples
javarecursionvectorruntime-errorjoptionpane

Unpredictable java program runtime error on JOptionPanel


I wrote a code whose aim is to create samples given a population. For example if I give a population of four elements ( 0, 1, 2, 3 ) and the samples are made of 1 element the output will be 0 1 2 3 Every value printed on a JOptionPane.

If the samples are made by two elements the output would be: 00 01 02 03 10 11 12 13 20 21 23 30 31 32 33

If the saples are made by three elements the output would be: 000 001 002 003 010 011 012 013 and so on

I wrote this program recursively, so that it could run for every sample's dimension.

The program stops when it should print values(contained in a vector) on the JOptionPane, and I can't understand the motivation. Here is the code:

import java.util.Vector;
import javax.swing.JOptionPane;


public class Combo {

/**
 * Function that recursively prints samples
 * @param n size of samples
 * @param popolazione elements of the population
 * @param combinazione the vector that contains the uncomplete sample
 */
public static void stampa(int n, Vector<Integer> popolazione, Vector<Integer> combinazione){
    // exit condition, when n equals 0 the function doesn't self-calls
    if(n==0) JOptionPane.showMessageDialog(null, combinazione);

    // for every element of the population the function adds this element
    // at the previous combination
    for(int x = 0; x<popolazione.size();x++){
        Vector<Integer> aggiunta = new Vector<Integer>(combinazione);
        aggiunta.add(x);
        stampa(n-1, popolazione, aggiunta);
    }
}

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    // creation a vector population with 4 elements
    Vector<Integer> popolazione = new Vector<Integer>();
    for(int x = 0; x < 4; x++) popolazione.add(x);

    // creation of samples
    stampa(1, popolazione, new Vector<Integer>());
}
}

Where could be my error?


Solution

  • In your method stampa(), I believe you want to change this

    if(n==0) JOptionPane.showMessageDialog(null, combinazione);
    

    to this

    if (n < 1) {
      JOptionPane.showMessageDialog(null,
          combinazione.get(n));
      return;
    }