0

I have this ArrayList of data filled with numbers from a file I open which I would like to be able to generate random numbers from it by entering the size of the sample and the number of samples I want. So I have the following...

private JTextField jtfN = new JTextField();// where i enter the amount of samples
private JTextField jtfn = new JTextField();// where i enter the size of samples
private ArrayList< Double> data = new ArrayList< Double>();

I have two text fields one named jtfn(size of sample) and one jtfN(amount of samples) which are where I enter the values. Then from that i have a button named jbtnGenerate whch when i click I want it to generate random numbers from data with the jtfn and jtfN entered above then putting it in a TextArea named jta

That's where I open files and add the numbers into data

if( jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ) {

String file = jfc.getSelectedFile().getPath();
String line = null;
String[] ch;

try {   
    FileReader fr = new FileReader( file);
    BufferedReader br = new BufferedReader(fr);
    data.clear();
    while( (ligne=br.readLine())!=null ) {
        ch = line.split( ";" );
        for (int i = 0; i < ch.length; i++) {
            data.add( Double.parseDouble(ch[i]) );  
        }                       
    }

    br.close();             
}
catch( IOException ioe ) {
}           

}

That's my listener for the button "generate" where I would like for the actions to happen.

       jbtnGenerer.addActionListener( new ActionListener() {
        public void actionPerformed( ActionEvent ae ) {

            try {                   

             int sampSize = Integer.parseInt(jtfn.getText());
             int nSamples = Integer.parseInt(jtfN.getText());

            double samps[][] = new double[nSamples][sampSize];

            for(int i = 0 ; i < nSamples; i++){
                for(int j = 0 ; j < sampSize; j++)
                    samps[i][j] = (Double) data.toArray()[ rng.nextInt() % data.size() ];
              }


                jta.append(samps.toString());

            } catch (NumberFormatException e) {

            }
        }

    });

Thanks for the help

Ramy
  • 7
  • 4
  • 1
    I definitely wouldn't name your variables that way... very easy to create bugs. – Alex Nov 05 '13 at 00:41
  • I am completely distracted by wondering what jtfn and jtfN mean. – placeybordeaux Nov 05 '13 at 00:42
  • 1
    Just for clarification purposes, it looks like you want to take N samples of n doubles from data, right? – MSalmo Nov 05 '13 at 00:54
  • @Peter, I would guess Java text field, with `n` and `N` being the variables that they capture. But that doesn't make it right... – x4nd3r Nov 05 '13 at 00:57
  • They are textfields where I enter the values. jtfn is where I set the size of the samples and jtfN is where I set the amount of samples i wanna take. And these numbers are take from data which is an ArrayList of doubles – Ramy Nov 05 '13 at 01:32

1 Answers1

0

There's no such thing as true random in code, but there are pseudo-random number generators. In order generate integers and create groups of samples, you'll need to create a Random object. You'll have to import it first:

    import java.util.Random;

Then, you'll have to create it and give it a seed in your function. The most commonly used seed is the current time in milliseconds:

    Random rng = new Random( System.currentTimeMillis() );

My guess is that you'd want to first parse the input, so something like

    int sampSize;
    int nSamples;
    if( !jtfn.getText().isEmpty() )
     sampSize = Integer.parseInt(jtfn.getText());
    if( !jtfN.getText().isEmpty() )
     nSamples = Integer.parseInt(jtfN.getText());

Then you'll have to make something to hold your samples. A 2D array would work fine.

    double samps[][] = new double[nSamples][sampSize];

From there, you'll need to populate your array of sample groups. A single loop works fine, but for readability's sake, here's a nested for-loop:

    for(int i = 0 ; i < nSamples; i++){
      for(int j = 0 ; j < sampSize; j++)
        samps[i][j] = data.get( rng.nextInt(data.size()) );
    }

Where rand() is the RNG function your language would use. From there, you'll have an N x n sized array filled with samples.

MSalmo
  • 352
  • 1
  • 14
  • When I try to add that it gives me that data[ rand() % data.length ]; length cannot be resolved or is not a field also I can't parse them into an int cause they're text fields – Ramy Nov 05 '13 at 01:36
  • I updated my answer. This of course assumes that data is already populated with doubles. Edit: Judging by the updated question, it looks like you do. – MSalmo Nov 05 '13 at 01:44
  • I added more information in my main answer and yes when I open the file it adds doubles into data but for some reason this one is giving me errors samps[i][j] = data.toArray()[ rand() % data.length ]; – Ramy Nov 05 '13 at 01:47
  • I tried to cast it to a double and change the length to size samps[i][j] = (Double) data.toArray()[ rand() *data.size() ]; the error is that rand is undefined for the new type actionlistener – Ramy Nov 05 '13 at 01:50
  • Sorry about that. Updated again to discuss the `Random` object and how to generate integers from it. Hope that's useful. `System.currentTimeMillis()` returns the current time in milliseconds. – MSalmo Nov 05 '13 at 01:57
  • I also tried with the samps[i][j] = (Double) data.toArray()[ (int) Math.random() * data.size() ]; but its giving a Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "" then it says the error is at the int sampSize = Integer.parseInt(jtfn.getText()); int nSamples = Integer.parseInt(jtfN.getText()); – Ramy Nov 05 '13 at 02:08
  • Use the `Random` object as I stated above. The `Integer.parseInt()` issue is stemming from there not being any input for the text boxes to parse. You will need to surround it with a try-catch statement or precede it with an if-statement that checks the length of the strings in your text boxes. Something like `if(!jtfn.getText().isEmpty())` will do. – MSalmo Nov 05 '13 at 02:16
  • Yea, that's what I had done added a try catch for it. For some reason when i enter the values lets say 50 and 200 and click generate it doesn't show anything in my text area. Edit: I loaded the filed before and when I did then click generate it's giving me an index out of bounds error "Exception in thread 'AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -47217 at Intervalleur$3.actionPerformed(Intervalleur.java:166)' – Ramy Nov 05 '13 at 02:25
  • For that, you can find the answer [here](http://stackoverflow.com/questions/2088016/add-a-new-line-to-the-end-of-a-jtextarea). To add an entire group of answers, you'll just have to use a for-loop which loops from 0 to n of whichever group you desire. As an example, `for(int i = 0 ; i < n ; i++ ) jta.append(samps[0][i].toString());` appends the first group in the array to the TextArea. – MSalmo Nov 05 '13 at 02:35
  • Oh I know that. What I mean is that when I go select open a text file then enter say 50,200 clicking generate its giving the out of bounds exception to `samps[i][j] = (Double) data.toArray()[ rng.nextInt() % data.size() ];` – Ramy Nov 05 '13 at 02:47
  • Try simplifying the random element selector to `data.get(rng.nextInt(data.size()));` I'll update it above. – MSalmo Nov 05 '13 at 02:57
  • I tried now what it does is sends me this in the text area `[[D@fdbc27` – Ramy Nov 05 '13 at 03:12
  • That's usually the output if you try to print out an array rather than the elements inside the array. What do you have in the `jta.append()` method? – MSalmo Nov 05 '13 at 03:23
  • `jta.append(samps.toString()+"\n");` I tried doing a for for it but it tells me cannot invoke toString() on the primitive double `for(int i = 0 ; i < data.size() ; i++ ) jta.append(samps[0][i].toString());` Edit: I fixed the for `for(int i = 0 ; i < data.size() ; i++ ) jta.append(String.valueOf(samps[0][i])+"\n");` but after it runs it gives me index out of bounds for the append part – Ramy Nov 05 '13 at 03:32
  • Accoring to the answer [here](http://stackoverflow.com/questions/5766318/converting-double-to-string) , try `for(int i = 0 ; i < n; i++) jta.append(String.valueOf(samps[0][i]));` to convert doubles to strings. That'll get you your first group of n samples. You can set up a nested for-loop to get the rest. – MSalmo Nov 05 '13 at 03:36
  • I made this `for(int i = 0 ; i < samps.length ; i++ ) { for(int j = 0 ; j < samps.length ; j++ ) jta.append(String.valueOf(samps[i][j])+"\n"); }` but it's giving me an out of bounds exception for `jta.append(String.valueOf(samps[i][j])+"\n");` I feel like my – Ramy Nov 05 '13 at 03:52
  • I think this worked was confusing things `for(int i = 0 ; i < nSamples ; i++ ) { for(int j = 0 ; j < sampSize ; j++ ) jta.append(String.valueOf(samps[i][j])+"\n"); }` – Ramy Nov 05 '13 at 03:56
  • Is there a way to format the answer to 6 decimals only I tried using string.format but it doesn't work – Ramy Nov 05 '13 at 04:29