0

I am trying to make a program that generates 100 integers from 0 to 25 and store them in 3 arrays: one for all the numbers, one for even, one for odd. I am having trouble with adding the variable n to my arrays. My .get is also not working well. Thanks!

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class randomdemo { 
    public static ArrayList randommethod()
    {
        int i = 0;

        ArrayList myArray = new ArrayList();
        ArrayList evenArray = new ArrayList();
        ArrayList oddArray = new ArrayList();

        while(i<=99)
        {
            Random rand = new Random();
            int n = rand.nextInt(25) + 0;

            myArray.add(n);

            if(myArray.get(i) % 1 == 0)
            {
                evenArray.add(n);
            }
            else
            {
                oddArray.add(n);
            }
            i++;
        }
        return myArray;
        return evenArray;
        return oddArray;
    }

    public static void main(String args[])
    {
        randommethod();
    }
}
Young Deezie
  • 145
  • 2
  • 12

2 Answers2

3

You can't have three returns from a single method, and you don't use the result anyway. Please don't use raw-types. And, you could make those List(s) static so you can use them after calling your method. You should declare your Random before starting your loop. Finally, even is % 2 == 0. Something like,

static List<Integer> myArray = new ArrayList<>();
static List<Integer> evenArray = new ArrayList<>();
static List<Integer> oddArray = new ArrayList<>();

public static void randommethod() {
    Random rand = new Random();
    for (int i = 0; i < 100; i++) {
        int n = rand.nextInt(26); // <-- n + 0 is n. 0 to 25.
        myArray.add(n);
        if (n % 2 == 0) { // <-- test n, no need to get it again.
            evenArray.add(n);
        } else {
            oddArray.add(n);
        }
    }
}

and then

public static void main(String args[]) {
    randommethod();
    System.out.println("All: " + myArray);
    System.out.println("Even: " + evenArray);
    System.out.println("Odd: " + oddArray);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

There are a few ways to do this.

Random rnd = new Random();
ArrayList<Integer> all = new ArrayList<Integer>();
ArrayList<Integer> even = new ArrayList<Integer>();

//Add 100 integers of all numbers
for(int x=0; x<100; x++)
    all.add(rnd.nextInt(26)) //26 gives random 0-25

//Add 100 integers of even numbers
int x=0;
while(x<100){
    int rand = rnd.nextInt();
    if(rand % 2 == 0){
       even.add(rand);
       x++
    }     
}

Generating odd numbers are same as the way you generate even numbers. Just change the condition to if (rand % 2 != 0)

user3437460
  • 17,253
  • 15
  • 58
  • 106