Corey
Corey

Reputation: 264

Getting characters from random number generator in Java

I am supposed to create a program that calls a method that generates permutations of the numbers 1 to 10. Basically, I'm supposed to fill an array with random numbers between 1-10 that never gets a repeat number, and gets different results every time I call the method. I used the Random() class but for some reason it is generating symbols, characters, and numbers. Here is my program:

import java.util.*;

 public class perms
   {
    public static void main(String[] args) 
    {
     int[] myPermutation;
     myPermutation = generatePermutation1To10();
     System.out.println(myPermutation);
    }

    private static int[] generatePermutation1To10() {
       Random rng = new Random();
       int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
       int[] finalNums = new int[nums.length];

       for (int k=0;k<finalNums.length; ++k)
       {
           int rnIdx = rng.nextInt(nums.length-k);
           finalNums[k] = nums[rnIdx];
           nums[rnIdx] = nums[nums.length-k-1];
       }
       return finalNums;
   }
 }

Upvotes: 0

Views: 144

Answers (2)

rgettman
rgettman

Reputation: 178333

Those characters aren't your random characters instead of random integers. That is the default output of the toString() method in Object, which arrays (which are objects too) don't override.

[T]his method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

You probably saw something like this:

[I@68111f9b

The [I is Java's code for array ([) of int (I), and the 68111f9b is the hexadecimal output of the hash code for the array.

Try

System.out.println(Arrays.toString(myPermutation));

Upvotes: 2

ataylor
ataylor

Reputation: 66109

Your code is correct, but you're seeing the internal representation of the array. Use Arrays.toString to print out your array:

System.out.println(Arrays.toString(myPermutation));

Upvotes: 0

Related Questions