java 这个代码的输出是重复的,我不能只得到一个输出

laawzig2  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(181)
for (int a = 0; a < noofvisitors; a++) {
    String visitorname = Helper.readString("\nEnter visitor name > ");
    for (int j = 0; j < visitorList.size(); j++){
        if (visitorname.equalsIgnoreCase(visitorList.get(j).getVname())) {
            System.out.println("\n*** Visitor already regisitered ***");
        } else {
            String visitornric4 = Helper.readString("Enter visitor last 4 alphanumeric digit of nric > ");
            int visitorcontact = Helper.readInt("Enter visitor contact > ");
            String date = Helper.readString("Enter visiting date > ");
            Visitor visitorinfo = new Visitor(visitorname, visitornric4, visitorcontact, date, patientname);
            visitorList.add(visitorinfo);
            visitorinfo.displayvisitorinfo();
            System.out.println("\n*** Visitor is regisitered successfully ***");
            patientList.get(i).setVisitorCount(noofvisitors);
            System.out.println("\n*** Please proceed to ward ***");

我正在尝试让它输出"\n*** Visitor already regisitered ***

k4emjkb1

k4emjkb11#

在判断visitorname是否已经存在之前,需要将输入的visitornamevisitorList中的所有名称进行比较,因此您的循环是不正确的。您可以更改逻辑,首先遍历所有元素,只有在没有找到匹配项时才继续添加新的Visitor,但这不会非常有效。
如果您将访问者List替换为HashMap<String,Visitor>,效率会高得多。
然后你可以检查一个访问者名字是否已经在预期的恒定时间内存在(而不是循环所需的线性时间):

if (visitorMap.containsKey(visitorname.toLowerCase()) {
        System.out.println("\n*** Visitor already regisitered ***");
    } else {
        String visitornric4 = Helper.readString("Enter visitor last 4 alphanumeric digit of nric > ");
        int visitorcontact = Helper.readInt("Enter visitor contact > ");
        String date = Helper.readString("Enter visiting date > ");
        Visitor visitorinfo = new Visitor(visitorname, visitornric4, visitorcontact, date, patientname);
        visitorMap.put(visitorname.toLowerCase(),visitorinfo);
        visitorinfo.displayvisitorinfo();
        System.out.println("\n*** Visitor is regisitered successfully ***");
        patientList.get(i).setVisitorCount(noofvisitors);
        System.out.println("\n*** Please proceed to ward ***");
   }
tyky79it

tyky79it2#

在决定用户是否已经注册之前,您需要迭代整个列表。

boolean alreadyRegistered = false;
for (int j = 0; j < visitorList.size(); j++){
  if (visitorname.equalsIgnoreCase(visitorList.get(j).getVname())) {
    alreadyRegistered = true;
    break;
  }
}

或者,更简单地说:

boolean alreadyRegistered = visitorList.anyMatch(v -> visitorname.equalsIgnoreCase(v.getVname()));

然后您可以决定要做什么:

if (alreadyRegistered) {
  // Print message about being already registered.
} else {
  // Get the details of the new visitor.
}

相关问题