0

I have this code that would randomize the number inputs but should not include 0 and 50 and above digits... how should i do it? Thanks

import java.util.*;
public class RndomA {
    public static void main(String[]args){
 
       int[]A=new int [10]; 
        Scanner in=new Scanner(System.in);

 
 System.out.println("Numbers to be randomize:");

 for(int a=0;a<A.length;a++){
   Random r=new Random();
     A[a]=in.nextInt();
int randomPosition = r.nextInt(A.length-1);
     if(A[a]<=50 && A[a]>=1){

    int temp = A[a];
    A[a]=  A[randomPosition];
    A[randomPosition]=temp;
     }
        System.out.print(A[randomPosition]+" ");
        }
    }}

Edited by Nathan_11: n/a

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by stultuske
0

well, you have the amount of elements in the array (10), so, you know that the indexes of your array will vary from 0 to 9.

create an empty array of ten elements
write a method that returns a random number between -1 and 10 (so including 0 and 9, but not -1 and 10), randomIndex, for instance
iterate over your original array and for each element
1. search an unused index in the second array, by using the randomIndex method
2. verify that the element with this index has not yet been filled (you'll have to make a little check for this)
3. if it's already used, repeat step two untill you get an unused index
4. store the element you were iterating over in the new array with the index returned from randomIndex

this would be 'a' way to do this, you'll propably find a lot better ways, but since I don't have much time at the moment, I can't look too long over it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.