如何打印语句外循环以避免重复?

时间:2013-08-09 23:51:50

标签: java loops for-loop

我希望我的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");
    }
}

5 个答案:

答案 0 :(得分:3)

在循环之前声明变量然后在循环中执行你的东西,比如如果找到变量就添加一个变量,然后如果它大于0则将其打印出来。像这样......

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

当然这段代码不起作用,但它是一个开始。为了您的学习经历,我将让您使用您的代码实现这个想法。

答案 1 :(得分:2)

这是因为如果你只在循环上面声​​明变量并且只在循环中初始化所述变量,当你试图在循环之外打印它们时,并不能保证它们会被初始化。

所以,也许你想要这样的东西:

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

答案 2 :(得分:2)

这不会有意义.. 如果你想要比试试这个......

        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的匹配数,请试试这个

我假设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());

答案 3 :(得分:0)

如果计划在循环退出后访问它,则需要在循环外声明一个变量。

答案 4 :(得分:-2)

您需要在循环外部初始化变量。试试这个:

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