简体   繁体   中英

What if the declared variable in for each loop will print outside of the foor loop

I tried for each loop to find duplicates in an array, if I printing the variable "i" outside of the for each loop, it is providing unexpected output.

Expected: Related errors as like the variable is not declared(as the declared variable is local)

package Login;

public class DupsArray {

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 3};
        int length = a.length;
        for (int i : a) {
            for (int j = i + 1; j <= length - 1; j++) {
                if (a[i] == a[j]) { 
                    System.out.println("Found duplicate" + a[i]);
                    break;
                }

                System.out.print(i);    
            }
        }
    }
}

11Found duplicate3

You are using i to iterate the values (not indexes) of array a and j to iterate indexes .

Suggestion: instead of using an array you can use an ArrayList and make you code much simpler:

Iterate the list and for any item compare array.indexOf(item) with array.lastIndexOf(item) - if they're different you found a duplicate!

I think you should do it without an enhanced for -loop, because index comparison is needed to avoid false positives, eg you compare element i == 3 to element a[j] == 3 , which might be the same, but how do you want to determine that? To get around it, you would need an indexOf , so it would boil down to index comparison again.

I would use two classic for -loops and compare the indexes, skipping equal ones:

public static void main(String args[]) throws Exception {
    // the source to be investigated
    int[] a = {1, 2, 3, 3};
    // a container for duplicates found
    Set<Integer> dups = new HashSet<>();

    // iterate your elements of the source array
    for (int i = 0; i < a.length; i++) {
        // compare each one to the others
        for (int j = i + 1; j < a.length; j++) {
            // find out if the elements are equal
            if (a[i] == a[j]) {
                // if they are, add it to the set of duplicates
                dups.add(a[i]);
                // as an alternative, you could print them here, too
                // System.out.println("Duplicate found: " + a[i]);
            }
        }
    }

    // print the duplicates found
    System.out.println("Duplicates found: ");
    dups.forEach(d -> System.out.println(d));
}

Please read the code comments and note that you don't have to store the duplicates in case you just want to print them. Storing is needed for further processing or printing it some time later, maybe on demand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM