0

I am new in java and I have a question about how to create a random array method with a number in the range 1-50

I need to give him the size of the array and he should create an array by the size I gave it to him and the elements of this array from 1-50

I try this code but it's never working with me

public class NewClass {
     public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the number ");
    int r = input.nextInt();
    int[] list = new int[r];
    for (int i=0; i<10; i++){
        int n = (int)(Math.random()*50 + 1);
        list[i] = n;

        System.out.println(list[i] + " ");
    }

 }
  • What is the expected out put – seenukarthi Mar 08 '20 at 12:49
  • `I try this code but it's never working with me` - what is not working for you? – Arvind Kumar Avinash Mar 08 '20 at 12:51
  • 1
    Does this answer your question? [java - How do I create an int array with randomly shuffled numbers in a given range](https://stackoverflow.com/questions/15196363/java-how-do-i-create-an-int-array-with-randomly-shuffled-numbers-in-a-given-ra) – T A Mar 11 '20 at 09:52

5 Answers5

3

Your for loop should be
for (int i = 0; i < r; i++)

Eduard Dubilyer
  • 991
  • 2
  • 10
  • 21
1

This is one place I would definitely use streams. They have been around since Java 8 and everyone should be familiar with them. Even those new at coding in Java.

        Random r = new Random();
        int nElements = 10;
        int maxElement = 50;
        List<Integer> nums = r.ints(nElements, 1, maxElement+1).boxed().sorted()
            .collect(Collectors.toList()); 

        System.out.println(nums);

Here is the explanation.

  • The first element to r.ints is the quantity. The next two are start and ending range. Since the range is exclusive, 1 must be added to include the maxElement as a possibility.
  • Boxed() maps the ints to Integer objects to be collected into a List.
  • Sorted() does what you would expect.
  • And the collector puts them into a List
WJS
  • 36,363
  • 4
  • 24
  • 39
0

So I see two problems in your code:

  1. You didn't close your class. So just append your code with a }
  2. If you want to fill the whole Array and not just the first 10 Elements change your for-loop-condition to i<list.length (you would also get an IndexOutOfBoundsException if your Array length is smaller than 10)

Hope I could help you ;)

Lucas Mähn
  • 736
  • 2
  • 6
  • 19
0

You should create methods to do it in a modular way. Other improvement you can do is to use Random::nextInt to get rid of multiplying and casting. Given below is a sample program:

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

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the array: ");
        int r = input.nextInt();
        int[] list = new int[r];
        init(list);
        print(list);
    }

    static void init(int list[]) {
        Random random = new Random();
        for (int i = 0; i < list.length; i++) {
            list[i] = random.nextInt(50) + 1;
        }
    }

    static void print(int list[]) {
        for (int i : list) {
            System.out.print(i + " ");
        }
    }
}

A sample run:

Enter the size of the array: 3
4 1 38 

[Update] Posting the following code to answer OP's requirement (mentioned in the comment below) of also sorting the elements:

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

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the array: ");
        int r = input.nextInt();
        int[] list = new int[r];
        init(list);
        System.out.println("Original list:");
        print(list);
        System.out.println("\nSorted list:");
        Arrays.sort(list);
        print(list);

    }

    static void init(int list[]) {
        Random random = new Random();
        for (int i = 0; i < list.length; i++) {
            int n = (int) (Math.random() * 50 + 1);
            list[i] = random.nextInt(50) + 1;
        }
    }

    static void print(int list[]) {
        for (int i : list) {
            System.out.print(i + " ");
        }
    }
}

A sample run:

Enter the size of the array: 3
Original list:
27 5 37 
Sorted list:
5 27 37 
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
-1

Try this one:

Random rand = new Random();
int my_num = 1 + rand.nextInt(50);
Xalva
  • 1
  • How is this any better than `(int)(Math.random()*50 + 1);` that is already in the original poster's code? And where is there any textual explanation in your answer? – Hovercraft Full Of Eels Mar 08 '20 at 12:50
  • where I put it? – TalalAlosaimi Mar 08 '20 at 12:51
  • Hi Xalva, well structure answers attract up-votes on stack overflow, well structured means to explain clearly how your solution answers the question, you do this with words, code and where possible show the output of your code in the context of the question. Also its always a good idea once you have identified the problem to search on Stack Overflow to see if the problem has been solved previously and then just link to the existing solution. More help here https://stackoverflow.com/help/how-to-answer – Nigel Savage Mar 08 '20 at 13:25