-1

I tried a program where I take an integer array and randomise values in it. but I am not able to understand why but am getting a crazy output which displays special characters and all. what's wrong with my question. Here is my code:

import java.util.Random;

public class Q2d {

    public static void shuffle(int[] arr) {

        int n = arr.length;
        Random random = new Random();
        random.nextInt();
        for (int i = 0; i < n; i++) {
            int change = i + random.nextInt(n - i);
            int temp = arr[i];
            arr[i] = arr[change];
            arr[change] = temp;
        }
    }

    public static void main(String args[]) {

        int[] arr = { 1, 2, 3, 4, 5, 6 };
        shuffle(arr);
        System.out.println(arr);

    }
}
Arturo Volpe
  • 3,442
  • 3
  • 25
  • 40
  • That is almost certainly the case, but for future notice you should probably include a sample of the "crazy output"... – dcsohl Dec 09 '13 at 21:28

2 Answers2

2

You are attempting to print the array object. Arrays are objects too, but they don't override Object's toString() method, which is responsible for the "crazy output".

Use Arrays.toString():

System.out.println(Arrays.toString(arr));
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

I'm pretty sure you asked this question like 20 minutes ago and in it instead of

System.out.println(arr);

you had

for(int i:arr){
    System.out.println(i);
}

which is correct...

Embattled Swag
  • 1,479
  • 12
  • 23
  • I got the answer but was just thinking if there is any better way to do it. – user3084380 Dec 09 '13 at 21:40
  • I think this is probably the most direct way of doing it but rgettman's answer is good too. – Embattled Swag Dec 09 '13 at 21:42
  • Using a `for` loop means you have to concern yourself with the implementation details of the array, particularly with the type of elements in the array. With `Array.toString()`, you don't ever have to worry about that, which is handy if you have to change array types due to something like design changes. – ajp15243 Dec 09 '13 at 21:54