如何从2个不同的数组中选择字符串并随机组合每个数组中的元素?

时间:2016-11-02 16:37:52

标签: java arrays

用户必须在2个不同的数组中输入任意数量的名词和形容词。(每个数组最少3个)。示例数组用户输入apple,pair,orange。数组b =绿色,甜,烂,蓝色。现在我需要随机选择形容词并将它们添加到名词中。像甜苹果,腐烂的对等...我不能使用相同的单词两次,我需要使用math.Random()。你怎么能这样做?

public static void main(String[] args) {
    String[] Noun = new String[4];
    String[] Adj = new String[4];
    int numbOfNouns = 0;
    int numbOfAdj = 0;

    Scanner kb = new Scanner(System.in);
    System.out.println("How many nouns ? min 3");
    numbOfNouns = kb.nextInt();

    while (numbOfNouns < 3) {
        System.out.println("How many nouns ? min 3");
        numbOfNouns = kb.nextInt();
    }

    System.out.println("Enter " + numbOfNouns + " nouns");
    for (int i = 0; i <= numbOfNouns; i++) {
        Noun[i] = kb.nextLine();
    }

    System.out.println("How many adjectives ? min 3");
    numbOfAdj = kb.nextInt();


    while (numbOfAdj < 3) {
        System.out.println("How many adjectives ? min 3");
        numbOfAdj = kb.nextInt();
    }

    System.out.println("Enter " + numbOfAdj + " adjectives");

    for (int i = 0; i <= numbOfAdj; i++) {
        Adj[i] = kb.nextLine();
    }

}

1 个答案:

答案 0 :(得分:2)

您可以使用专为列表设计的Collections shuffle方法:

List<String> arrayNoun = Arrays.asList(Noun);
Collections.shuffle(arrayNoun);

List<String> arrayAdj = Arrays.asList(Adj);
Collections.shuffle(arrayAdj);

顺便说一句,我认为你必须像这样修复整个代码:

public static void main(String[] args) {
    // when you ask user to enter number of objects in your array then you cannot define fix array size!
    String[] Noun;
    String[] Adj;

    int numbOfNouns = 0;
    int numbOfAdj = 0;

    Scanner kb = new Scanner(System.in);

    // the whole while loop can handle reading the number of nouns and so there is no need to call this code once before the loop!
    while (numbOfNouns < 3) {
        System.out.println("How many nouns ? min 3");
        numbOfNouns = kb.nextInt();
        kb.nextLine(); // get enter key after number enter
    }

    // here you define size of your array according to user input
    Noun = new String[numbOfNouns];

    System.out.println("Enter " + numbOfNouns + " nouns");
    for (int i = 0; i < numbOfNouns; i++) {
        Noun[i] = kb.nextLine();
    }

    while (numbOfAdj < 3) {
        System.out.println("How many adjectives ? min 3");
        numbOfAdj = kb.nextInt();
        kb.nextLine(); // get enter key after number enter
    }

    Adj = new String[numbOfAdj];

    System.out.println("Enter " + numbOfAdj + " adjectives");

    for (int i = 0; i < numbOfAdj; i++) {
        Adj[i] = kb.nextLine();
    }

    List<String> arrayNoun = Arrays.asList(Noun);
    Collections.shuffle(arrayNoun);

    List<String> arrayAdj = Arrays.asList(Adj);
    Collections.shuffle(arrayAdj);
}