0

i am trying to print a random array with a command-line argument so that it would take in a number such as 7 and print 7 random values

EDIT:

for example if i said 7

it would produce 1876379

import java.util.Random;
import java.util.Scanner;

public class exercise26 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter array size");
    int n = input.nextInt();
    Random rd = new Random(); // creating Random object
    int[] arr = new int[1];
    for (int i = 0; i < n; i++) {
      arr[i] = rd.nextInt(); // storing random integers in an array
      System.out.println(arr[i]); // printing each array element
    }
  }
}
nice
  • 25
  • 5
  • Just FYI random numbers on computers aren't all that random. If you want truly random, you really need an "Infinite Improbability Drive" (https://www.psychologytoday.com/us/blog/pura-vida/201806/the-whale-magrathea-teaches-the-meaning-life). If you haven't read Hitchhiker's guide to the galaxy, you should check it out. :) – ControlAltDel Dec 08 '20 at 02:38
  • 1
    Does this answer your question? [Generating random array of fixed length (Java)](https://stackoverflow.com/questions/58874938/generating-random-array-of-fixed-length-java) – SwissCodeMen Dec 08 '20 at 12:09

2 Answers2

1

The question implies that you want to generate n digits (i.e. numbers between 0 and 9 inclusive).

This can be done in a single statement with Random.ints:

Random random = new Random();
random.ints(n, 0, 10).forEach(System.out::println);

If you particularly want them in an array:

int[] result = random.ints(n, 0, 10).toArray();

An array can be converted to a string with Arrays.toString to be printed. That creates a string with a fixed format "[a, b, c]". If you just want the items concatentated:

System.out.println(String.join("", result));

or

Arrays.stream(result).forEach(System.out::print);

or a for loop.

sprinter
  • 27,148
  • 6
  • 47
  • 78
0

Use System.currentTimeMillis to initialize your random, and initiate your array with the right dimention

    Random rd = new Random(System.currentTimeMillis); // creating Random object
      int[] arr = new int[n]; // the n value you got earlier from the user
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80