簡體   English   中英

如果每個循環中的聲明變量將在foor循環外打印怎么辦

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

我嘗試為每個循環在數組中查找重復項,如果我在每個循環的外部打印變量“ i”,則會提供意外的輸出。

預期:相關錯誤,例如未聲明變量(因為聲明的變量是局部變量)

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);    
            }
        }
    }
}

11找到重復項3

您正在使用i來迭代數組a (而不是索引),而使用j來迭代index

建議:可以使用ArrayList而不是使用數組,並使您的代碼更簡單:

迭代列表,對於任何itemarray.indexOf(item)array.lastIndexOf(item) -如果它們不同,則會發現重復項!

我認為您應該在沒有增強的for循環的情況下執行此操作,因為需要索引比較以避免誤報,例如,將元素i == 3與元素a[j] == 3 ,這可能是相同的,但是該怎么做您要確定嗎? 為了解決這個問題,您將需要一個indexOf ,因此它將歸結為再次進行索引比較。

我將對-loops使用兩個經典方法for並比較索引,跳過相等的索引:

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));
}

請閱讀代碼注釋,並注意,如果只想打印副本,則不必存儲副本。 需要存儲以進行進一步處理或稍后再打印(可能是根據需要)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM