I need help with generating random numbers between 0 and y and x being the amount generated in java, as you can see I am almost there, but sorting them at the end, is giving me trouble please help me get this corrected!
//imports
import java.util.Scanner;
import java.util.Random;
//Class
public class RandomGen {
//Main Method
public static void main(String[] args) {
//Prepare Scanner
Scanner randomScanner = new Scanner(System.in);
System.out.println("Between 0 and what integer would you like to generate random Integers? ");
int y = randomScanner.nextInt();
System.out.println("Please Specify the number of Random integers you would like:");
int x= randomScanner.nextInt();
Random pseudo = new Random();
//Initialize Random
for(int i =0; i<x; i++) {
System.out.println(pseudo.nextInt(y+1));
}
}
}
//This code Generates the Randoms Just Fine! Now I need them sorted! //The Code below these lines has too many syntax errors //What Can I add to the above code to make this a simple organization of //this information, I need an array created and then have it organized. //Below is my failed attempt at it, can anyone keep the ABOVE code simple?
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class RandomInt {
public static void main(String[] args) {
int[] increasingRandoms(int x, int y);
{
//establishing an array
Scanner randomScanner = new Scanner(System.in);
System.out.println("Between 0 and what integer would you like to generate random Integers? ");
y = randomScanner.nextInt();
System.out.println("Please Specify the number of Random integers you would like:");
x= randomScanner.nextInt();
//Setting x to pseudoRandom into an array in order to sort later
int[] pseudoRandom = new int [x];
for(int i =0; i< x; i++){
Random pseudo = new Random();
pseudoRandom[i] = pseudo.nextInt(y);
}
//returning an array in ascending order
Arrays.sort(pseudoRandom);
return pseudoRandom;
}
for(int number : increasingRandoms(y, x)) {
System.out.print(number + " ");
}
}
}
Try storing the array returned by increasingRandoms(x,y) in a variable first then use the variable in the enhanced for loop instead of using the method directly.
int[] temp=increasingRandoms(y, x);
for(int number : temp) {
System.out.print(number + " ");
}
Also, I dont see why you should be creating a new object on each loop iteration, its better to create one Random object before entering the loop and then just call nextInt(int) in the loop
int[] pseudoRandom = new int [x];
Random pseudo = new Random();
for(int i =0; i< x; i++){
pseudoRandom[i] = pseudo.nextInt(y);
}
如果您能够使用Java 8,那么这是一个很好的简单解决方案:
int[] myRandomNumbers = new Random().ints(x, 0, y).sorted().toArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.