-2
import java.util.Random;

public class Hi {

    public static void main(String[] args) {
        Random random = new Random();
        int integer = random.nextInt(100 - 0) + 0;

        System.out.println(sumDigits(integer));
    }
    public static int sumDigits(int n) {

        int sumOfInteger = 0;
        while (n != 0) {
            sumOfInteger += n % 10;
            n /= 10;
        }
        return sumOfInteger;
    }
}

I need to use arrays instead of regular. This is what I have to do Program that generates 100 random integers between 0 and 9 and displays the count for each number. (Hint: Use an array of ten integers, say counts, to store the counts for the number of 0s, 1s, . . . , 9s.) I am getting single numbers but not the count. But at the same time I have to use arrays.

import java.util.Arrays;
import java.util.Random;

public class Hw7Problem3 {

    public static void main(String[] args) {

    System.out.println(sumDigits());

    }
    public static int[] sumDigits(int random) {

        int[] digits = new int[10];
        for (int i = 0; i < 100; i++){
          digits[(int) (Math.random() * 10)]++;
        }
        return digits;
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Wilson
  • 1
  • 3

2 Answers2

0

I hope this will help you:

int counts[] = new int[10];
for(int i = 0; i < 100; i++) {
    int rnd = random.nextInt(10);
    counts[rnd] = counts[rnd] + 1;
}

so in counts[N] you can find how many times N was random generated.

DontRelaX
  • 744
  • 4
  • 10
0

Your assignment was to create 100 random integers between 0 and 10. So we need to start with an array of digits with which to count. We could use a Math.random() and multiply by 10 (to get a number from 0 to 9 inclusive) and increment that index in digits. Something like

int[] digits = new int[10];
for (int i = 0; i < 100; i++)
  digits[(int) (Math.random() * 10)]++;

Then you print it perhaps with

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

Across two runs I got

[11, 11, 9, 9, 6, 11, 9, 13, 11, 10]

and

[8, 6, 5, 11, 10, 9, 13, 10, 15, 13]

Which seem to suggest that it works.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • @Wilson Yes, because that's my answer as a method but you forgot `Arrays.toString()` so you get the default toString from Object. `System.out.println(Arrays.toString(sumDigits()));` – Elliott Frisch Nov 29 '14 at 07:51