为if-else块中的变量的不同值指定不同的操作

时间:2013-10-18 13:40:32

标签: java if-statement

我是Java的初学者(之前我学过C语言),这似乎是一个简单的问题,但我被困在这里。如果我想对变量的不同值采取某些操作怎么办?

例如 -

if(r==1)

else if(r==2)
   //take action2
else if(r==3)
  //take action3
  .
  .
  . 

等等。

如何对“r”的任何值进行概括(假设r的值可以是1到任何数字,在运行时间确定)?

我将'r'的值作为参数传递给包含上述代码块的函数。

编辑:让我更清楚地解释一下这个问题。

现在假设我有一个这样的列表:

   Items: a b c d

T1:       1 1 0 1
T2:       0 1 0 0
T3:       1 1 0 0
T4:       0 0 1 1
T5:       1 0 1 1

(这里'1'表示:在T1或T2或T3或T4或T5中出现该项目。 '0'表示:没有发生)

现在r = 1:我必须在T1,T2,T3,T4,T5中分别计算出a,b,c,d的出现次数。

对于r = 2:我必须计算(a,b),(a,c),(a,d),(b,c),(b,c)和(c, d)T1,T2,T3,T4,T5。

对于r = 3:我必须计算(a,b,c),(a,c,d)......的出现次数等等。

我希望你明白这一点。

我已经为上面的排列编写了代码,并计划将其作为列表传递,并将'r'作为参数传递。

(对于那些了解数据挖掘的人,您可能已经猜到我正在尝试实现其中一种算法!)

1 个答案:

答案 0 :(得分:0)

您已经提到,您的问题中引用的表在内部表示为2D数组,因此计算Tx具有r组合的项目数就像计算有多少行一样简单其中r个“1”。

   Items: a b c d

T1:       1 1 0 1
T2:       0 1 0 0
T3:       1 1 0 0
T4:       0 0 1 1
T5:       1 0 1 1

代表为;

int[][] data=new int[noOfT][noOfLetters];

然后使用as;

   public static int count(int[][] arrayToCount, int noOfCombinations){

       int count=0;
       for(int i=0;i<arrayToCount.length;i++){
           int thisRowCount=0; //how many items are on this row

           for(int j=0;j<arrayToCount[i].length;j++){
               if (arrayToCount[i][j]==1){
                   thisRowCount++;
               }
           }


           if (thisRowCount<=noOfCombinations){ //if this row has the a sufficient number of items increase the count
               count++;
           }
       }

       return count;
   }