簡體   English   中英

如何在循環外打印語句以避免重復?

[英]How to print statement outside loop to avoid duplicates?

我希望我的print語句不在循環中,因此該語句不會一遍又一遍地打印相同的內容。 下面的for循環僅將一個數組中的一個數字與另一個數組進行比較,以查找已找到多少個匹配項。 定義上面的變量並打印下面的語句會導致“變量未初始化錯誤”,這是可以理解的。

for (int i = 0; i < 6; i++)
{
    int chkNum = myArray[i];
    int lottMtch = count(chkNum, rndNum);

    if (lottMtch > 0)
    {
        System.out.println(lottMtch + "matches found");
        System.out.print(chkNum);
    }
    else {
        System.out.print("no matches found");
    }
}

在循環之前聲明變量,然后在循環中進行操作,例如在發現變量時將其添加到變量中,然后在變量大於0時將其打印出來。類似這樣的事情...

int var = 0;
for(...) {
   if(found)
       var++;
}
if(var > 0)
    sysout(var);

當然,此代碼將不起作用,但這只是一個開始。 為了您的學習經驗,我將讓您通過代碼來實現這個想法。

這是因為,如果僅在循環上方聲明變量,並且僅在循環中初始化變量,則當您嘗試在循環外打印變量時,無法保證它們將被初始化。

因此,也許您想要這樣的事情:

int lottMtch = 0;

for (int i = 0; i < 6; i++)
{
    int chkNum = myArray[i];
    lottMtch += count(chkNum, rndNum);
    //System.out.print(chkNum); this would not really make sense outside of the loop
}

if (lottMtch > 0)
{
    System.out.println(lottMtch + "matches found");
}
else 
{
    System.out.print("no matches found");
}

如果您想要的話,這真的沒有道理。

        int lottMtch[]=new int[myArray.length];
           Arrays.fill(lottMtch, 0);
            for (int i = 0; i < 6; i++)
            {
                int chkNum = myArray[i];
               lottMtch[i] = count(chkNum, rndNum);

            }
            for (int i = 0; i < 6; i++)
            {
                       if (lottMtch[i] > 0)  
                            System.out.println(lottMtch[i] + " matches found "+ myArray[i]);
            }

如果您rndNummyArray找到rndNum匹配數, rndNum嘗試以下操作

在這里我假設rndNmglobal

        int lottMtch=0;

            for (int i = 0; i < 6; i++)
            {

               lottMtch += count(myArray[i], rndNum);

            }

                       if (lottMtch> 0)  
                            System.out.println(lottMtch + " matches found "+ rndNum);

根據評論中討論的嘗試此..

Map<Integer,Integer> map = new HashMap<Integer,Integer>();


       for (int i = 0; i < 6; i++)
         {
             Integer chkNum = myArray[i];
            Integer cnt = (Integer)count(myArray[i], rndNum);
              if(cnt>0)
              {
                  if(map.get(chkNum)==null)
                     map.put(chkNum,1);
                  else
                     map.put(chkNum, map.get(chkNum)+1);
              }

         }

         for (Object key : map.keySet()) 
             System.out.println(map.get(key) + " matches found "+key.toString());

如果您打算在循環退出后訪問它,則需要在循環外聲明一個變量。

您需要在循環外初始化變量。 嘗試這個:

int chkNum = 0;
int lottMtch = 0;

for (int i = 0; i < 6; i++)
{
    chkNum = myArray[i];
    lottMtch = count(chkNum, rndNum);

}

if (lottMtch > 0)
{
    System.out.println(lottMtch + "matches found");
    System.out.print(chkNum);
}
else {
    System.out.print("no matches found");
}

暫無
暫無

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

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