-1

I am creating an array with a size based on user input and the elements will be randomly generated (0-20). The problem I'm having is I don't know how to use the same array with the same randomly generated elements into different methods.

import java.util.Scanner;
import java.util.Random;
public class RandomArrays { 

    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);
        System.out.print("Enter the number of elements: ");
        int n = in.nextInt();

        array(n);
    };


    public static int[] array(int n) {
        Random r = new Random();
        int random = 0;
        int[] array = new int[n];

        System.out.print("Array: ");
        for (int i = 0; i < array.length; i++) {
            random = r.nextInt(20);
            System.out.print(array[i] + random + " ");
        }
        evenElement(a);
    return array;
    };


    public static int[] evenElement(int[] a) {
        Random r = new Random();
        int random = 0;
        for (int i = 0; i < a.length; i++) {
            random = r.nextInt(20);
            System.out.print(a[i] + random + " ");
        }
        return a;
    };


};

Yes, this is homework for me but it's keeping me from making any progress.

2 Answers2

0

When you run

array(n)

it returns an Array. So save it to a new variable like:

int[] myArray = array(n);

and the pass myArray to evenElement

Tizianoreica
  • 2,142
  • 3
  • 28
  • 43
  • I tried this but now it's giving me an array with different elements, I need the same array with the same elements as printed in the `array` method. – Hussein Srour Nov 23 '16 at 11:44
0

Keep back the int[] that the method is returning

int[] myUsefulArray = array(n);

after that you can simply do:

System.out.print("Enter the number of elements: ");
int n = in.nextInt();
int[] myUsefulArray = array(n);
evenElement(myUsefulArray )
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97