0

Working on building an array that can generate random integer values inside an array. It prints the random numbers but it prints it like this [10][2][5][7][6][2][4][7][2][10][0]--->(down the side)--------> and want it to print like this [10,7,5,9,4,3,4,7,2,3] (one line).

   public class ArrayLab
{
    //array instance variable
    private int[] array1 = new int[10];

    //array constructor
    public ArrayLab(int integer)
    {
        //class parameter = 10
        int[] array1 = new int[]{integer};

    }

    public void initialize()
    {
         //allow randomization of numbers inside the array field.

        System.out.println(Arrays.toString(array1)); 
        //prints [0,0,0,0,0,0,0,0,0,0] which is ok

        System.out.println();
        for (int iteration = 0; iteration < array1.length; iteration ++)
        {
            Random number = new Random(); 
            number.nextInt(10);
            int n = number.nextInt(11);
            int[] array1 = new int[]{n};

            System.out.println(Arrays.toString(array1));
           //prints down the side. Want on one line?
        }

    }
}
7
  • Please read the JavaDoc: docs.oracle.com/javase/7/docs/api/java/io/…. Commented Oct 20, 2015 at 23:53
  • 1
    Use print() instead of println() (print line). Commented Oct 20, 2015 at 23:55
  • Or just have a look at System.out.print() instead of println() to avoid the newline being put at the end. Commented Oct 20, 2015 at 23:56
  • Ah ok, just got in the habit of using "println" thanks. Commented Oct 20, 2015 at 23:57
  • Btw do you know what int[] array1 = new int[]{integer}; and int[] array1 = new int[]{n}; mean and what happen there? Looks like a programming error to me. Commented Oct 21, 2015 at 0:01

1 Answer 1

2

Just change

System.out.println(Arrays.toString(array1)); 
//new output
System.out.print(Arrays.toString(array1));

another way you can get this done is by using a for loop to iterate through the array in similar fashion

for( int i = 0; i < array1.length; i++ ){
    System.out.print(array1[i]+" ");
}

for the random numbers

Random ran = new Random();
for( int i = 0; i < array1.length; i++ ){
    int number = ran.nextInt((max - min) + 1) + min;
    //insert the maximum and min values for your generator
    array1[i] = number;
Sign up to request clarification or add additional context in comments.

1 Comment

That makes it print like this [0,0,0,0,0,0,0,0,0,0] which is great! But how would I integrate the random numbers inside of this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.