如何在java中保持文本的随机性?

yjghlzjz  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(567)

我只是想知道,也许你能帮我。这是代码,也许你可以编辑一下。

import java.util.Scanner;
public ststic void main string(args[]){
    System.out.println("I want to keep randomize between  following texts:")
    //abc_123_def
    //jaofn_3vfdsa
    //nabdoew-8943
}
4dbbbstv

4dbbbstv1#

我想这就是你想要的。。。

public static void main(String[] args) {
 //task: show one of these texts randomly every time the user answers "yes"
    String[] text = {"abc_123_def", "jaofn_3vfdsa", "nabdoew-8943"};
    boolean bored = false;
    Scanner s = new Scanner(System.in);

    while (!bored) {
        System.out.println("Would you like to keep randomizing?");
        if (s.nextLine().equals("yes")) {
            int rand_n = (int) Math.round(Math.random() * 2);
            System.out.println("Random text: " + text[rand_n]);
        }
        else {bored = true;}
    }
}
dsekswqp

dsekswqp2#

你可以储存不同的 String 在一个 List ,然后洗牌

System.out.println("I want to keep randomize between  following texts:");
List<String> texts = Arrays.asList("abc_123_def", "jaofn_3vfdsa", "nabdoew-8943");

Collections.shuffle(texts);
System.out.println(texts); // [jaofn_3vfdsa, abc_123_def, nabdoew-8943]

Collections.shuffle(texts);
System.out.println(texts); // [abc_123_def, nabdoew-8943, jaofn_3vfdsa]

您可以自定义打印,使用 join 例如

System.out.println(String.join(", ", texts)); // abc_123_def, nabdoew-8943, jaofn_3vfdsa

相关问题