查看arraylist中是否存在名称,如果存在,请询问新名称

时间:2018-01-04 12:30:37

标签: java arraylist

public Event(String name, int numberOfTries) {
    this.name = name;
    this.numberOfTries = numberOfTries;
}

public String getName() {
    return name;
}

public int getNumberOfTries() {
    return numberOfTries;
}

public String toString() {
    return name + ", " + numberOfTries;
}

public void addEvent() {
    scan = new Scanner(System.in);
    eventList.add(new Event("Jacob", 5));

    System.out.print("Event name: ");
    String name = scan.nextLine();
    boolean match = true;
    for (int i = 0; i < eventList.size(); i++) {
        if (eventList.get(i).getName().equalsIgnoreCase(name)) {
            match = false;
            if (!match) {
                System.out.println(name + " has already been added\n");
            }

            else {
                System.out.println("Event name: ");
            }
        }
    }
    System.out.print("Attempts allowed: ");
    int numberOfTries = scan.nextInt();
    scan.nextLine();

    eventList.add(new Event(name, numberOfTries));

    System.out.println(name + " added\n");

}

当我输入预先存在的名称“Jacob”时,它会像这样:

“活动名称:雅各布 Jacob已被添加

尝试允许:“

我想让程序问我一个新名字,因为Jacob已经存在。 但我似乎无法回到循环中。

我不想使用地图或类似的东西,只有ArrayLists。

1 个答案:

答案 0 :(得分:0)

首先,您无法定义match=false;,然后询问if(!match)。它永远都是真的。

相反,在循环外部编写if ... else语句。当循环结束时,它将检查匹配布尔值。 if (!match) { System.out.println(name + " has already been added\n");} else { System.out.println("Event name: "); match = true;}

然后引入一个检查match = true的循环,以便用户可以尝试多次:while(!match){ scan = new Scanner(System.in); eventList.add(new Event("Jacob", 5)); System.out.print("Event name: "); String name = scan.nextLine(); for (int i = 0; i < eventList.size(); i++) { if (eventList.get(i).getName().equalsIgnoreCase(name)) { match = false; } } if (!match) { System.out.println(name + " has already been added\n"); eventList.removeLast();} else { System.out.println("Event name: "); match = true;} }

请记住将匹配变量初始化为false,然后再检查它。