Java程序没有改变名称

时间:2017-09-20 03:44:44

标签: java random

之前,我发布了一个无法正常运行的程序。当我输入名字时,我需要它随机化并将两个名字配对在一起。我的代码如下

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("How many names would you like to enter?");
    int n = scan.nextInt();
    System.out.println("Enter the " + n + " names: ");
    String[] names = new String[n];
    for (int i = 0; i < names.length; i = i + 1) {
        names[i] = scan.nextLine();
    }
    List<String> AllNames;
    // Prints the names in a list
    AllNames = new ArrayList<>(Arrays.asList(names));
    for (int i = 0; i < names.length; i = i + 2) {
        System.out.print(names[i]);
        if (i < names.length) {
            System.out.print(" " + "&" + " " + names[i + 1]);
        }
        System.out.println();
    }
    Random rand = new Random();
    Collections.shuffle(AllNames, rand);
    scan.close();
}

收到的输出是:

' & a'
'b & c'

2 个答案:

答案 0 :(得分:0)

您需要首先对列表进行随机播放,然后打印出来。

编辑:显示重复的名称检测,奇数n的错误。

import java.util.*;

public class TestX {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("How many names would you like to enter?");

        int n = scan.nextInt();
        scan.nextLine(); // to capture new line after the n

        if (n % 2 != 0) {
            System.out.println("ERROR!!!");
            System.exit(0);
        }

        System.out.println("Enter the " + n + " names: ");
        List<String> nameList = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            String name = scan.nextLine();

            if (nameList.contains(name)) {
                System.out.println("Already exists " + name);
            } else {
                nameList.add(name);
            }
        }

        scan.close();

        Collections.shuffle(nameList);

        for (int i = 0; i < nameList.size(); ) {
            if ((i + 1) >= nameList.size()) {
                System.out.println(nameList.get(i));
                i++;
            } else {
                System.out.println(nameList.get(i) + " & " + nameList.get(i + 1));
                i += 2;
            }
        }

    }
}

答案 1 :(得分:0)

您需要在nextLine()之后调用nextInt()(使用一个尾随新行字符)。您似乎不需要数组(因为您无论如何都使用List)。在尝试打印随机对之前,您应shuffle。在访问i + 1处的元素之前,您需要根据长度(或大小或n)检查i + 1。像,

Scanner scan = new Scanner(System.in);
System.out.println("How many names would you like to enter?");
int n = scan.nextInt();
scan.nextLine();
System.out.println("Enter the " + n + " names: ");
List<String> names = new ArrayList<>();
for (int i = 0; i < n; i++) {
    names.add(scan.nextLine());
}
Collections.shuffle(names);
for (int i = 0; i < n; i += 2) {
    System.out.print(names.get(i));
    if (i + 1 < n) {
        System.out.print(" & " + names.get(i + 1));
    }
    System.out.println();
}