【问题标题】:Reject duplicate user input java拒绝重复的用户输入java
【发布时间】:2019-01-16 03:31:08
【问题描述】:

我对编程很陌生,我希望能够防止用户重复输入字符串。但到目前为止,下面的代码不起作用(或被程序完全忽略)。提前致谢!!

    boolean current = false;

    for (int i = 0; i < dogs.size(); i++) {
        System.out.println("Dog name: ");
        String dogName = scan.nextLine().toLowerCase();
        if (dogName.equals(dogs.get(i).getName())) {
            auction.add(new auction(dogName));
            System.out.printf(dogName + " has been put up for auction in auction #%d", i);
            System.out.println();
            current = true;

        }//code below does not work
        if (auction.contains(dogName)) {
            System.out.println("Error: this dog is already up for auction.");
        }

    }
    if (current == false) {
        System.out.println("Error: no such dog in the register");
    }

【问题讨论】:

  • 您需要搜索所有dogs,而不仅仅是dogs(i) 以验证是否有重复项。
  • 什么是“拍卖”类?

标签: java eclipse


【解决方案1】:

你可以使用 lambda

boolean hasThisDog = dogs.stream().anyMatch(d -> dogName.equals(d.getName()));
if(hasThisDog){
  System.out.println("Error: this dog is already up for auction.");
}else{
  auction.add(new auction(dogName));
   System.out.printf(dogName + " has been put up for auction in auction #%d", i);
   System.out.println();
   current = true;
}

或者您可以使用 SET。 SET 默认防止重复。你可以在这里阅读Java: Avoid inserting duplicate in arraylist

Set<Dog> set = new HashSet<Dog>();
set.add(foo);
set.add(bar);

public class Dog{
     @Override
     public boolean equals(Object obj) {
       if (obj instanceof Dog)
         return (this.name= obj.name) 
      else
         return false;
    }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 2018-07-03
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多