【问题标题】:Check List if data exists then input value again检查列表是否存在数据然后再次输入值
【发布时间】:2021-08-20 08:34:32
【问题描述】:

我的主要目标是确定输入的号码是否在列表中不重复,否则用户需要更新一个新号码。系统会不断要求用户输入不重复的数字。

我目前正在努力获取逻辑以检查我的列表是否包含重复的 ID。如果有人输入了重复的 ID,则会提示他重新输入一个新号码。将再次检查新编号,直到系统满足没有重复元素为止。下面的函数返回一个整数,将在main方法中添加到Course类型的List中。

以下是我的函数的sn-p:

public static int ifExist(List<Course> courselist, Iterator<Course> itr,  int personid) {
        
        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        boolean found = false;
        boolean flag = false;
        int personid2 = personid;
        String value = null;
        
        while (itr.hasNext()) {
                Course courseItr = itr.next();
                if(courseItr.getPersonID() == personid) {
                    found = true;
                    flag = true;
                    
                    while(found == true) {
                        System.out.print("No duplicate number is accepted. Please enter another number: ");
                        do {
                            // must be a digit from 1 - 10,000
                            String digit = "\\d{1,10000}";
                            value = input.nextLine();
                            flag = value.matches(digit);
                            if (!flag) System.out.print("Please a number only!: ");
                        } while (!flag);
                        personid2 = Integer.parseInt(value);
                        
                        if(personid2 != courseItr.getPersonID()) {
                            found= false;
                        }
                    }
                }
        }
        return personid2;
        
    }

执行 Course 程序时的输出如下所示。请注意,输入 no 1 意味着添加课程列表。

Please select your choice: 1

Enter the person ID: 1
Enter the person name: Alysa
Enter the title of the course: Maths
Enter the year of joining: 2021
Enter the fee of the course: 20.50
New Course has successfully been added.

Please select your choice: 1

Enter the person ID: 1
No duplicate number is accepted. Please enter another number: 1
No duplicate number is accepted. Please enter another number: 1
No duplicate number is accepted. Please enter another number: 1
No duplicate number is accepted. Please enter another number: 2
Enter the person name: Maria
Enter the title of the course: Biology
Enter the year of joining: 2021
Enter the fee of the course: 25.99
New Course has successfully been added.

Please select your choice: 1

Enter the person ID: 2
No duplicate number is accepted. Please enter another number: 2
No duplicate number is accepted. Please enter another number: 2
No duplicate number is accepted. Please enter another number: 2
No duplicate number is accepted. Please enter another number: 1
Enter the person name: Peter
Enter the title of the course: Chemistry
Enter the year of joining: 2021
Enter the fee of the course: 50.50
New Course has successfully been added.

如上图,说明我的 ifExist 方法不起作用(试图让逻辑正确)。两个人的ID相同,比如1。

当我尝试显示课程列表时

Please select your choice: 3
Person ID: 1, Name: Alysa, Title: Maths, Year: 2021, Fee: $20.5.
Person ID: 2, Name: Maria, Title: Biology, Year: 2021, Fee: $25.99.
Person ID: 1, Name: Peter, Title: Chemistry, Year: 2021, Fee: $50.5.

我已经用谷歌搜索过了,但似乎我要么必须使用 Set 删除任何重复项,要么使用 equals/hashcode()。不过,如果有经验丰富的 Java 程序员帮助澄清或提供有关如何解决此问题的任何想法,我将不胜感激。

新增方法

public static void addCourse(List<Course> courselist, Course course) {
        //check if the id is the same or not
        
        ListIterator<Course> itr = courselist.listIterator();
        
        try {
            @SuppressWarnings("resource")
            Scanner input = new Scanner(System.in); 
            int personid, year;
            String author, title;
            double fee;
                
            System.out.print("\nEnter the person ID: ");
            personid = input.nextInt();
            personid = ifExist(booklist, itr, personid);
            course.setPersonDd(personid);

...
...
...
courselist.add(new Course(personid, author, title, year, fee));
            System.out.println("New Course has successfully been added.");

} catch {
}
}       

谢谢。期待其他开发者的来信。

问候, 西蒙妮11

【问题讨论】:

  • 我认为问题不在那些方法上,而是在您获得 personID 并获得其他数据后您的列表是否确定您将该课程对象添加到相同的确切列表中尝试添加断点你的方法然后使用你的 ide 的调试模式它会帮助你
  • 能否也包括调用ifExist的方法?
  • 是的。我在 main 方法中有一个 addCourse 方法。此方法将添加信息。如果我输入原始 int 类型的 ID。它的值被传递给 ifExist 方法,然后返回一个整数。这个整数将作为 course.setPersonID(return integer) 设置到我的 Course 对象上。然后我将对象 Course 添加到列表中, courselist.add(new Course(info, etc));
  • @TimMoore 你的意思是递归函数?我做了,但没有工作。我认为我的逻辑还不存在。一旦之前的 ID 和新的 ID 比较,newID 应该会返回。但是,如果我输入一个新号码,当前系统会用最新的号码重复以前的号码。
  • 不,我不是那个意思。我想看看调用上述方法的代码。这个错误部分与它的使用方式有关。

标签: java list arraylist


【解决方案1】:

关于你的第一种方法

问题在于迭代器。当用户在2之后输入1时,迭代器已经通过了ID为1的Course,因此无法检测到重复ID。因此,每次用户输入新数字时,都必须重新开始迭代。

List&lt;Course&gt; courselist 参数未使用。

话虽如此,这个程序在逻辑上并没有优化。 ifExists(,) 方法应该只用于搜索具有相同 ID 的课程。至于处理用户输入,应该完全在方法之外完成。

这是ifExists(,) 方法的示例

public static boolean ifExists(int id, Iterator<Course> iterator){
    while (iterator.hasNext()) {
        Course next = iterator.next();
        if (next.id == id) return true;
    }
    return false;
}

然后在 main 方法中,您给用户的消息是基于此方法返回的值。这是一个例子:

Scanner scanner = new Scanner(System.in);
int id = scanner.nextInt();
while (ifExists(id)) {
    System.out.println("Duplicated ID! Please try another number.");
    id = scanner.nextInt();
} // If ifExists(id) returns false, continue to the code below to enter personal details

关于第二种方法

使用HashSet 代替ListIterator。您可以直接调用HashSet.contains(Obj) 来检查集合中是否已经存在Course,而无需循环遍历项目。虽然List也有这个方法,但是它会循环遍历所有的item,和你做的差不多。

这是因为 HashSet 按哈希码而不是添加顺序对项目进行排序,但 List 没有。因此,当您调用contains 方法时,它会查找条目号。 (插入哈希码)。

【讨论】:

  • 非常感谢您的 2 段代码。我已经遵循算法。但它根本不起作用。输入 1 两次,问题继续输入人名,而不是验证是否出现了相同的 ID。我还没有使用过 HashSet,因为我更愿意先解决这个问题。
  • @guyonstuckoverflow 我更新了我的代码中的一些小错误。 1. scanner.nextInt() 而不是 next() 2. 我应该在找到重复项时立即结束迭代,而不是等待整个迭代。除了上述问题之外,代码应该可以正常工作。也许您在问题中未显示的其他地方存在错误
  • 谢谢你。它仍然不起作用。如果这在 Course 类中有效,我将更改我的 List 以查看是否可以消除问题
  • @guyonstuckoverflow 如果还是同一个bug,可以尝试自己调试。或者,您可以将当前代码附加到问题中并让其他人看到。如果是另一个错误,您应该提出一个新问题,但请确保遵守行为准则。
  • 谢天谢地,我终于解决了这个问题。我正在使用 LinkedHashSet 类的 Set 接口。我创建了一个方法,如果我的集合不包含重复的 ID 并且在我的集合中添加了一个新的 ID,则该方法返回 true,如果重复,它将继续迭代,直到它变为 false。因此,我重写了两个方法,例如 equals 和 hashcode(),它们只限制了我的课程类中的重复 ID。我参考了您的第二个代码 sn-p 并创建了自己的逻辑。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多