簡體   English   中英

Java.如何在for循環中使用多個變量並迭代多個對象?

[英]Java.How to use multiple variables and iterate over a multiple objects in for loop?

首先,我是 Java 的新手

我正在嘗試

for(forWriting  f : treeSet, forDrawing f2 : treeSet2)

但它不是那樣工作的

它僅在我使用一個變量並迭代單個 object 時才有效,就像那樣

for(forWriting  f : treeSet)

我該如何在 Java 中做到這一點? 謝謝你的幫助!

不想做像你問的那樣的事情很清楚,更具可讀性。在 java 中,你必須使用 for 循環遍歷單個可迭代的 object。 如果您要迭代的兩個結構的長度相同,您可以編寫一個 for 循環並以這種方式從每個變量中獲取元素(在偽代碼中)

for(int i = 0; i< treeSet.Lenght; i++) {
   // get the i-th value from treeSet 
   // get i-th valut from treeSet2

   // ... execute other statements
}

除了這個答案之外,您可能還需要確保 1) 遍歷每個元素和 2) 防止 IndexOutOfBound-Exceptions(偽):

int max_length = max(treeSet1.length, treeSet2.length);
for(int i = 0; i < max_length; i++) {
    if(i < treeSet1.length) {
        forWriting f = treeSet1.get_by_index(i);
        // Do stuff for forWriting here
    }
    if(i < treeSet2.length) {
        forDrawing f2 = treeSet2.get_by_index(i);
        // Do stuff for forDrawing here
    }
}

暫無
暫無

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

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