简体   繁体   中英

How to randomize an array of a String so it is different every time though the loop

So I am making a description generator and am splitting a text file at a ":". So if the text file had "dog:fish:cat:bird", my code splits it at the ":" and randomly picks one. However, when I print out my ending results, the output is all the same. It will randomly pick the words in the array but then if I said generate it 4 times, it would be the same thing 4 times. So where is my logic wrong on how to approach this? I want it to print 4 random different things. My code is below:

public class Generator {

public static void main(String[] args) 
{
    Scanner scanner = new Scanner(System.in);
    Random r = new Random();

    System.out.print("Enter a file name: ");
    String fName = scanner.nextLine();
    File infle = new File(fName);
    Scanner read = new Scanner(infle);

    System.out.print("Enter number to make: ");
    int things = scanner.nextInt();
    System.out.println();
    System.out.println("Here are " + things + " things: ");
    System.out.println();


    //gets random animal
    String animal = read.nextLine();
    String[]anm1 = animal.split(":");
    int rnd_Animal = r.nextInt(anm1.length);
    String rndAnimal = (anm1[rnd_Animal]);


    //gets random adjective
    String adj = read.next();
    String []adj1 = adj.split(":");
    int rndAdj = r.nextInt(adj1.length);
    String randomAdj = (adj1[rndAdj]);


    for(int i=0; i <things; i++)
    {
        System.out.println(randomAdj + " " + rndAnimal);}

So, my output would print like: "sweaty fish" as many times as I entered for it to be generated. How can I get it to say "sweaty fish","smelly dog","slow fish" if I entered 3 descriptions to be generated? Thank you for any help.

The problem is that you get the value for rndAnimal and randomAdj outside the for loop. So it gets the value randomly ONLY ONCE and displays it four times. To solve the problem, assign the value to the two Strings inside the loop.

for(int i=0; i<things; i++){

    //gets random animal 
    String animal = read.nextLine();
    String[]anm1 = animal.split(":"); 
    int rnd_Animal =r.nextInt(anm1.length); 
    String rndAnimal =(anm1[rnd_Animal]); 

    //gets random adjective 
    String adj = read.next(); 
    String []adj1 = adj.split(":"); 
    int rndAdj = r.nextInt(adj1.length);
    String randomAdj = (adj1[rndAdj]);

    System.out.println(randomAdj + " " + rndAnimal);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM