Java方法中的嵌套For循环以检查重复项

问题描述

我是一名初学者,几天来我一直在尝试调试我的代码,以找出为什么我在 isDuplicate 中的循环似乎无法正常工作。我已经在网站上搜索了一些想法,但似乎没有一个解决我的问题。

目标是让用户输入一个项目,然后调用方法来检查该项目是否已经在数组中。如果不是,则应添加。如果是重复的,应该给出错误信息。

我只能为此使用循环,因为目标是学习 Java 中各种循环的实现。

当我运行程序时,它说第一个输入的项目是重复的。没有发现每个后续项目输入都是重复的。我的 for 循环迭代或我忽略的 if 语句中似乎存在逻辑错误

任何建议都非常感谢。我整个星期都在尝试在书籍和网上寻找答案,但遇到了障碍。

/*
 Grocery List that accepts input,sorts by item name,checks for duplicates and outputs list to user.
 */
public class Main {

    private static Scanner input = new Scanner(system.in);

    public static void main(String[] args) {
        int count = 0; // Number of items currently in the grocery list
        String[] groceryList = new String[6];

        /*
        invoke method to check for duplicate entries.
        use while loop for input from user
        */
        while (count < groceryList.length) {
            System.out.print("Enter a grocery item: ");
            String item = input.nextLine();
            isDuplicate(item,groceryList,count);
            groceryList[count] = item;
            count++;
        }

        // sort elements and use for-each loop to print list
        Arrays.sort(groceryList);
        System.out.println("Your Grocery List: ");
        for (String food : groceryList) {
            System.out.println(food);
        }
    }

    /*
       I kNow there is an issue with my loop but I Could not figure it out.
       Says first element is duplicate but no others.
       Cannot use collections. can only use for loops for this method.
     */
    public static boolean isDuplicate(String item,String[] list,int listcnt) {
        for (listcnt = 0; listcnt < list.length; listcnt++) {
            for (int j = listcnt + 1; j < list.length; j++) {
                if (list[j] == list[listcnt])
                    System.out.println("Sorry," + item + " is a duplicate.");
                return true;
            }
        }
        return false;
    }
}

解决方法

暂时忘掉 Java 代码,从逻辑上思考它,然后在脑海中想出一个算法。

您有一个项目 - 尚未在列表中(这很重要)。您有一个项目列表。您想查看该项目是否已在项目列表中。

你会如何为纸上的列表做这个?

  • 扫描项目列表?听起来不错
  • 这是否需要遍历列表两次?没有

您也不检查 isDuplicate 检查的结果并始终添加项目

isDuplicate(item,groceryList,count);
groceryList[count] = item;

通常在 Java 中,我们不使用 == 来比较对象:https://www.geeksforgeeks.org/difference-equals-method-java/

if (list[j] == list[i])
,

您的主要问题是您没有使用 isDuplicate() 的结果:

/*
 Grocery List that accepts input,sorts by item name,checks for duplicates and outputs list to user.
 */
public class Main {

    public static void main(String... args) {
        String[] groceryList = readGroceryList(6);
        // sort elements and use for-each loop to print list
        Arrays.sort(groceryList);
        print(groceryList);
    }

    private static String[] readGroceryList(int total) {
        Scanner scan = new Scanner(System.in);
        String[] groceryList = new String[total];
        int count = 0; // Number of items currently in the grocery list

        /*
        invoke method to check for duplicate entries.
        use while loop for input from user
        */
        while (count < groceryList.length) {
            System.out.print("Enter a grocery item: ");
            String item = scan.nextLine();

            if (isDuplicate(item,count))
                System.err.println("Sorry," + item + " is a duplicate.");
            else
                groceryList[count++] = item;
        }

        return groceryList;
    }

    private static void print(String[] groceryList) {
        System.out.println("Your Grocery List: ");

        for (String food : groceryList)
            System.out.println(food);
    }

    /*
       I know there is an issue with my loop but I could not figure it out.
       Says first element is duplicate but no others.
       Cannot use collections. can only use for loops for this method.
     */
    public static boolean isDuplicate(String item,String[] groceryList,int count) {
        for (int i = 0; i < count; i++)
            if (item.equals(groceryList[i]))
                return true;

        return false;
    }
}
,

我不明白您的 isDuplicate() 方法。以下是扫描数组中重复项的标准方法:

    public static boolean isDuplicate(String item,String[] list){
        //iterate the array
        for(String listItem : list){
            //check if "item" matches "listItem"
            if(item.equals(listItem)){
                return true;
            }
            //NOTE: if you want this to not be case sensetive,//e.g. if you want "somestring" to be equal to "SomeString",do
//            if(item.equalsIgnoreCase(listItem)){
//                return true;
//            }
        }
        //we only get this far in the method if the item is not in the list
        return false;
    }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...