0

I am trying to find a way to print the contents of the array, while using a for loop. This is a fairly new section in java to me, as I am a beginner. Any help is appreciate in concerns to my question. My question is would I move the "Random" assessor method into the mutator method or am I just completely wrong and have to do something else.

import java.util.Random;

public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;

public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];

// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
  arr[i] = rand.nextInt(MAX_VALUE) + 1;
     }
  } 
public void printArray( ) {

}

public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();

System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");

   }
}
Xzavier
  • 53
  • 7

3 Answers3

1

My question is would I move the "Random" assessor method into the mutator method or am I just completely wrong and have to do something else.

You don't have to. Just use a loop to iterate through the array which is already filled in the constructor.

public void printArray( ) {    
    for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
        System.out.println(arr[i]);    
    } 
}

By the way, with Java 8, you can write less lines of code to achieve the same result:

Arrays.stream(arr).forEach(System.out::println);
VHS
  • 9,534
  • 3
  • 19
  • 43
0
public void printArray() {

//Print array
System.out.println(Arrays.toString(arr));

//another method with for loop 

 for (int i = 0; i < arr.length; i++)
     {
       System.out.println(arr[i])
      }
}

Note there is plenty of other techniques

Tarek
  • 708
  • 5
  • 14
0

In terms of writing clean code, it would probably be good to move this bit of code into its own private method within the class, and calling that within the constructor.

public ArrayPractice() {
    // initialize array
    arr = new int[MAX_ARRAY_SIZE]; 
    populateArray();
}

private void populateArray() {
    // randomly fill array with numbers
    Random rand = new Random(1234567890);
    for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
       arr[i] = rand.nextInt(MAX_VALUE) + 1;
    }
 }

Then in your printArray() method you can loop through the array and call System.out.println( ) for each item.

public void printArray( ) {
   for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
   }
}

If you come from a more functional background, I can show you how to write this more functionally using Java 8 lambdas. Let me know.

Jordan Cutler
  • 562
  • 4
  • 14