1

I couldn't locate a homework tag but this is HOMEWORK.

I am looking to randomly assign a value to each letter while separating them by a comma and must use an array in the answer.

Here is what I attempted so far but am still some way off.

    double[] numbers = {5,4,6.2,1.5};
    char[] letters = {'a','v','c',d'};

    int temp = (int) (Math.random()*numbers.length);
    int woo = (int) (Math.random()*letters.length);


    for (int i = 0; i < letters.length; i++) {
        for (int j = 0; j < numbers.length; j++){
            System.out.print(letters[woo]);
            System.out.print(numbers[temp]);
            System.out.print(',');
        }
    }

I am hoping for an output of something like: d4, c1.5, v6.2, a5

Any help would be appreciated

  • 1
    Create the random indexes inside the inner `for` loop. – 001 Jan 05 '17 at 21:04
  • and you might want to use `char` and `double` instead of `int` – hotzst Jan 05 '17 at 21:07
  • Great thanks. i have moved the indexes in but now it look as if the letters are coming up more than once. any tips on how to make them appear just once? – A. Einstein Jan 05 '17 at 21:15
  • You are always using the same entries within the loop. You didn’t even make an attempt to use others. You are picking two random elements of either array *before* the loop, which is basically [like this](http://xkcd.com/221/)… – Holger Jan 06 '17 at 19:05

1 Answers1

0

You can shuffle the arrays using Collections.shuffle (or some custom implementation for a primitive array), and then iterate the arrays in parallel.

Double[] numbers = { 5.0, 4.0, 6.2, 1.5 };
Character[] letters = { 'a', 'v', 'c', 'd' };

Collections.shuffle(Arrays.asList(numbers));
Collections.shuffle(Arrays.asList(letters));

StringJoiner joiner = new StringJoiner(", "); // from Java 8
int length = Math.min(numbers.length, letters.length);
for (int i = 0; i < length; i++) {
    joiner.add(letters[i].toString() + numbers[i]);
}
System.out.println(joiner.toString());

Ideone Demo

Community
  • 1
  • 1
4castle
  • 32,613
  • 11
  • 69
  • 106