有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

用户必须在两个不同的数组中输入任意数量的名词和形容词。(每个阵列至少3个)。示例数组A用户输入apple、pair、orange。数组b=绿色、甜蜜、腐烂、蓝色。现在我需要随机选择形容词,并将它们添加到名词中。比如甜苹果,烂苹果等等。。。我不能用同一个词两次,我需要用数学。随机()。你怎么能做到

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) 个答案

  1. # 1 楼答案

    您可以使用为以下列表设计的集合洗牌方法:

    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);
    }