web-dev-qa-db-fra.com

Remplir un tableau avec des nombres aléatoires

Je dois créer un tableau à l'aide d'un constructeur, ajouter une méthode pour imprimer le tableau sous forme de séquence et une méthode pour remplir le tableau avec des nombres aléatoires du type double.

Voici ce que j'ai fait jusqu'à présent:

import Java.util.Random;


public class NumberList {


    private static double[] anArray;

    public static double[] list(){
        anArray = new double[10];   
        return anArray;
    }

    public static void print(){
        for(double n: anArray){
        System.out.println(n+" ");
        }
    }


    public static double randomFill(){

    Random Rand = new Random();
    int randomNum = Rand.nextInt();
    return randomNum;
    }

    public static void main(String args[]) {

    }


}

J'ai du mal à comprendre comment remplir le tableau avec les nombres aléatoires que j'ai générés dans la méthode randomFill. Merci!

5
JaAnTr

Vous devez ajouter une logique pour affecter des valeurs aléatoires à un tableau double [] à l'aide de randomFill method.

Changement

 public static double[] list(){
    anArray = new double[10];   
    return anArray;
 }

À

 public static double[] list() {
    anArray = new double[10];
    for(int i=0;i<anArray.length;i++)
    {
        anArray[i] = randomFill();
    }
    return anArray;
}

Vous pouvez ensuite appeler des méthodes, notamment list () et print () dans la méthode principale pour générer des valeurs doubles aléatoires et imprimer le tableau double [] dans la console.

 public static void main(String args[]) {

list();
print();
 }

Un résultat est le suivant:

-2.89783865E8 
1.605018025E9 
-1.55668528E9 
-1.589135498E9 
-6.33159518E8 
-1.038278095E9 
-4.2632203E8 
1.310182951E9 
1.350639892E9 
6.7543543E7 
4
MouseLearnJava

Cela semble un peu comme un devoir. Je vais donc vous donner quelques indices. La bonne nouvelle est que vous y êtes presque! Vous avez déjà fait l'essentiel du travail!

  • Pensez à une construction qui peut vous aider à itérer sur le tableau. Existe-t-il une sorte de construction (une boucle peut-être?) Que vous pouvez utiliser pour parcourir chaque emplacement du tableau?
  • Dans cette construction, pour chaque itération de la boucle, vous affecterez la valeur renvoyée par randomFill() à l'emplacement actuel du tableau.

Remarque: Votre tableau est double, mais vous renvoyez ints de randomFill. Il y a donc quelque chose que vous devez corriger ici.

2
Vivin Paliath

Vous pouvez utiliser IntStream (ints) ou DoubleStream double () disponible à partir de Java 8 en classe aléatoire. quelque chose comme cela fonctionnera, cela dépend si vous voulez un double ou un autre, etc. 

int [] array = new int [100000];

Aléatoire Aléatoire = Nouveau Aléatoire ();

array = random.ints (100000, 10,100000) .toArray ();

vous pouvez imprimer le tableau et vous obtiendrez 100 000 entiers aléatoires. 

2
Samir Ouldsaadi

Vous pouvez parcourir le tableau et à chaque itération appeler la méthode randomFill. Vérifiez-le:

import Java.util.Random;

public class NumberList {


    private static double[] anArray;

    public static double[] list(){
        anArray = new double[10];   
        return anArray;
    }

    public static void print(){
        for(double n: anArray){
            System.out.println(n+" ");
        }
    }


    public static double randomFill(){
        Random Rand = new Random();
        int randomNum = Rand.nextInt();
        return randomNum;
    }

    public static void main(String args[]) {
        list();
        for(int i = 0; i < anArray.length; i++){
            anArray[i] = randomFill();
        }
        print();
    }


}
1
jarz

Les gens ne voient pas les producteurs Nice Cool Stream partout dans les bibliothèques Java.

public static double[] list(){
    return new Random().ints().asDoubleStream().toArray();
}
0
Johannes Kuhn

Vous pouvez simplement le résoudre avec un for-loop

private static double[] anArray;

public static void main(String args[]) {
    anArray = new double[10]; // create the Array with 10 slots
    Random Rand = new Random(); // create a local variable for Random
    for (int i = 0; i < 10; i++) // create a loop that executes 10 times
    {
        anArray[i] = Rand.nextInt(); // each execution through the loop
                                        // generates a new random number and
                                        // stores it in the array at the
                                        // position i of the for-loop
    }
    printArray(); // print the result
}

private static void printArray() {
    for (int i = 0; i < 10; i++) {
        System.out.println(anArray[i]);
    }
}

La prochaine fois, veuillez utiliser la recherche sur ce site, car il s'agit d'une question très courante sur ce site et vous pouvez également trouver de nombreuses solutions sur Google.

0
user2655904

essaye ça:

public void double randomFill(){

  Random Rand = new Random();
  for(int i = 0; i < this.anArray.length(); i++){
    this.anArray[i] = Rand.nextInt();
  }
}
0
hawks

Vous pouvez appeler la méthode randomFill() dans une boucle et remplir votre tableau dans la méthode main() comme ceci.

public static void main(String args[]) {
    for(int i=0;i<anArray.length;i++){
        anArray[i] = randomFill();
    }
}

Bien que vous ayez besoin d'utiliser Rand.nextDouble() dans randomFill() car vous semblez avoir un tableau double à remplir.

double randomNum = Rand.nextDouble();
return randomNum;
0
SudoRahul

Si le caractère aléatoire est contrôlé comme ceci, il est toujours possible de générer un nombre quelconque de points de données d'une plage donnée. Si la méthode aléatoire en Java est uniquement utilisée, nous ne pouvons pas garantir que tous les nombres seront uniques.

package edu.iu.common;

import Java.util.ArrayList;
import Java.util.Random;

public class RandomCentroidLocator {

public static void main(String [] args){
	
	int min =0;
	int max = 10;
	int numCentroids = 10;
	ArrayList<Integer> values = randomCentroids(min, max, numCentroids);	
	for(Integer i : values){
		System.out.print(i+" ");
	}
	
}

private static boolean unique(ArrayList<Integer> arr, int num, int numCentroids) {

	boolean status = true;
	int count=0;
	for(Integer i : arr){
		if(i==num){
			count++;
		}
	}
	if(count==1){
		status = true;
	}else if(count>1){
		status =false;
	}
	

	return status;
}

// generate random centroid Ids -> these Ids can be used to retrieve data
// from the data Points generated
// simply we are picking up random items from the data points
// in this case all the random numbers are unique
// it provides the necessary number of unique and random centroids
private static ArrayList<Integer> randomCentroids(int min, int max, int numCentroids) {

	Random random = new Random();
	ArrayList<Integer> values = new ArrayList<Integer>();
	int num = -1;
	int count = 0;
	do {
		num = random.nextInt(max - min + 1) + min;
		values.add(num);
		int index =values.size()-1;
		if(unique(values, num, numCentroids)){				
			count++;
		}else{
			values.remove(index);
		}
		
	} while (!( count == numCentroids));

	return values;

}

}

0
Vibhatha Abeykoon

Probablement la manière la plus propre de le faire dans Java 8:

private int[] randomIntArray() {
   Random Rand = new Random();
   return IntStream.range(0, 23).map(i -> Rand.nextInt()).toArray();
}
0
Jeff smith

Cela vous donnera un tableau avec 50 nombres aléatoires et affichera le plus petit nombre du tableau. Je l'ai fait pour un travail dans mon cours de programmation.

public static void main(String args[]) {
    // TODO Auto-generated method stub

    int i;
    int[] array = new int[50];
    for(i = 0; i <  array.length; i++) {
        array[i] = (int)(Math.random() * 100);
        System.out.print(array[i] + "  ");

        int smallest = array[0];

        for (i=1; i<array.length; i++)
        {
        if (array[i]<smallest)
        smallest = array[i];
        }



    }

}

} `

0
Steven Hollinger