简体   繁体   English

Arrays 和 For 循环 - 打印随机元素时不正确的 output

[英]Arrays and For-loop - Incorrect output while printing Random elements

I am pretty new in this world, and I must say sometimes things that looks easy are pretty harsh.我在这个世界上很新,我必须说有时候看起来很容易的事情很苛刻。

I am stuck with a task that entails dealing with an array and for -loops.我被一项需要处理数组和for循环的任务困住了。

I should iterate over the array and for every iteration step print a different random string.我应该遍历数组并为每个迭代步骤打印一个不同的随机字符串。 My current code is not working correctly, the only thing I'm getting a random item and the same index printed multiple times.我当前的代码无法正常工作,唯一的事情是我得到一个随机项目并且多次打印相同的索引。

My output right now:我的 output 现在:

relax
2
2
2
2

How can I fix that and get a correct randomized output?我该如何解决这个问题并获得正确的随机 output?

My code:我的代码:

public static void main(String[] args) {
    int i;
    
    String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
     
    java.util.Random randomGenerator = new java.util.Random();

    int x = Cofee.length;
    int y = randomGenerator.nextInt(x);
    
    String frase = Cofee[y] ;
    System.out.println(frase);
    
    for(i = 0; i < Cofee.length; i++)
        System.out.println(y);      
}    

You assign a value to y once, and you print y repeatedly.y赋值一次,然后重复打印y The value of y doesn't change. y的值不会改变。 To do that, you would need to call randomGenerator.nextInt(x) for each iteration of the loop !为此,您需要为循环的每次迭代调用randomGenerator.nextInt(x)

However, if you want to randomize and print the array, use:但是,如果要随机化并打印数组,请使用:

public static void main(String[] args)  
{
    String[] coffee = {"pick it","drink it","relax","put it in a cup",};
    // this wraps the array, 
    // so modifications to the list are also applied to the array
    List<String> coffeeList = Arrays.asList(coffee);
    Collections.shuffle(coffeeList);
    
    for(String value : coffee)
        System.out.println(value);      
}

As an aside, don't use String coffee[] , but use String[] coffee .顺便说一句,不要使用String coffee[] ,而是使用String[] coffee Although Java allows putting the array type after the variable name, it is considered bad form.尽管 Java 允许将数组类型放在变量名之后,但它被认为是错误的形式。

Or use a list directly:或者直接使用列表:

public static void main(String[] args)  
{
    List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
    Collections.shuffle(coffeeList);
    
    for(String value : coffeeList)
        System.out.println(value);      
}

For that, you can implement a shuffling algorithm.为此,您可以实现洗牌算法。

It's not so scare as it might sound at first.它并不像一开始听起来那么害怕。 One of the famous classic shuffling algorithms, Fisher–Yates shuffle is relatively easy to grasp. Fisher-Yates shuffle是著名的经典洗牌算法之一,相对容易掌握。

The core idea: iterate over the given array from 0 to the very last index, and for each index swap the element that corresponds to the randomly generated index between 0 and the current index ( i ) with the element under the current index.核心思想:从0到最后一个索引遍历给定数组,并且对于每个索引,将对应于0当前索引( i ) 之间随机生成的索引的元素与当前索引下的元素交换。

Also, I would advise creating a separate array representing indices and shuffle it in order to preserve the array of string its initial state (you can omit this part and change the code accordingly if you don't need this).另外,我建议创建一个表示索引的单独数组并将其打乱,以保留字符串数组的初始 state(如果不需要,可以省略这部分并相应地更改代码)。

That's how it might be implemented:这就是它的实现方式:

public static final Random RANDOM = new Random(); // we need an instance for random to generate indices

A Fisher–Yates shuffle implementation: Fisher-Yates shuffle 实现:

public static void shuffle(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
        swap(arr, i, j);               // swapping elements `i` and `j`
    }
}

Helper-method for swapping elements:交换元素的辅助方法:

public static void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

Usage-example:用法示例:

String[] coffee = {"pick it","drink it","relax","put it in a cup"};
        
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
        
shuffle(indices);
        
for (int i = 0; i < coffee.length; i++) {
    String next = coffee[indices[i]];
    System.out.println(next);
}

Output: Output:

drink it
pick it
put it in a cup
relax

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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