控制台输入到arraylist java而没有重复输入

时间:2016-12-11 08:41:37

标签: java

任务:编写一个Java程序,允许程序用户只为一个字段中的8个运行轨道中的每一个分配一个运行器。

我能够让输入过程,数组列表,设置器和getter正常工作但我的问题是我难以理解如何限制8个通道的输入数量到每个跑步者只能分配一个通道的位置。这是我目前的输入代码:

public List<Item> createListOfCompetitors(){

    List<Item> newListOfCompetitors = new ArrayList<>();

    try (Scanner sc = new Scanner(System.in)) {
        do {
            System.out.println("Enter Competing Runner Name");
            String name = sc.nextLine();

            System.out.println("Assign a lane to the runner! ");
            while (!sc.hasNextDouble()) {
                System.out.println("Use a valid number");
                sc.next();
            }
            double lane = sc.nextDouble();
            Item item = new Item(name, lane);
            newListOfCompetitors.add(item);
            System.out.println("Enter Y to continue or N to quit");
            sc.nextLine();
        } while (sc.nextLine().equalsIgnoreCase("y"));
    }
    return newListOfCompetitors;
}

Dependencies in my program

1 个答案:

答案 0 :(得分:0)

我可能会使用车道地图来代表被占用的车道。这样,您可以添加一个条件,检查从控制台输入的通道是否已被占用。

public Map<Double, Item> createListOfCompetitors() {
    Map<Double, Item> lanes = new HashMap<>();

    try (Scanner sc = new Scanner(System.in)) {
        do {
            System.out.println("Enter Competing Runner Name");
            String name = sc.nextLine();

            System.out.println("Assign a lane to the runner! ");
            double lane;
            do {
                String lane = sc.nextLine();
                try {
                    lane = Double.parseDouble(lane);
                    if (lanes.get(lane) == null) {
                        lanes.put(lane, new Item(name, lane));
                        break;
                    } else {
                        System.out.println("Lane number already chosen.");
                    }
                } catch (NumberFormatException e) {
                    System.out.println("Please enter a valid lane number.");
                }
           } while (true);
       } while (sc.nextLine().equalsIgnoreCase("y"));
   }

    return lanes;
}