我有一个n个细胞阵列,细胞0有int 0,细胞1有In2等等。0,2,3,4,n.
我的目标是让用户在数组中选择一个值(而不是单元格#),只有在以下两个条件都为真的情况下,所选的值才变为零:
用户选择不可用的任何数字都将具有System.out.println ("Invalid number");。
编辑:我现在的问题是,当我有0,0,0, 4,5 ,6时,我可以选择4,5和6,并将其转化为零,即使这些数字没有除数。
我对代码的尝试,没有充分发挥作用:
int[] NumBox = new int[StartNum];
           for (int i = 1; i < NumBox.length+1; i++)
            {NumBox[i - 1] = i;}
 if (NumBox[pick-1]!= 0)
       { 
                    boolean hasDivisor = false;
                      for (int k = 1; k < NumBox.length+1; k++) 
                   {
                         if (NumBox[k] == 0) 
                         continue;
                         if (NumBox[pick-1] % NumBox[k] == 0) 
                         {
                           hasDivisor = true;
                           break;
                         }
                   }   
                    if (hasDivisor)
                     {
                      score1 = pick + score1;
                      NumBox[pick-1]=0;
                      }
                     else
                      System.out.println ("Invalid number");
        }谢谢你的帮助。
发布于 2014-03-18 03:34:08
您没有说明当前代码的问题所在,但我猜您可能想要更改此测试:
if (NumBox[pick-1] % NumBox[k] == 0)对此:
if (NumBox[pick-1] > NumBox[k] && NumBox[pick-1] % NumBox[k] == 0)这样你就不会认为一个数字是它自己的除数。
发布于 2014-03-18 03:34:42
好的..。这里有个方法。
1. Sort the array in ascending order.
2. For a given number/input say "n" at index say "i", 
   if any number before index "i" has number!=0 && n%number ==0, then it is divisible. Else, it is not divisible发布于 2014-03-18 04:04:49
简单的方法是
    1. Sort the array in ascending order.
    2. Now when the user selects a number, keep testing 
       the mod value from start until root(N) of that number. 
       If none mods to zero, then it doesn't have any divisors.第一部分应该很简单,第二部分应该类似于这个伪码。
boolean flag=false;
if(!(pick==0)){ // testing if it is already is not zero
for (int i = 0; i < args.length; i++) {
    if(pick%NumBox[i]==0){
        //divisor found
        flag=true;
        break;
    }else if(NumBox[i]>Math.sqrt(pick)){
        //No divisors found
        break;
    }
}
}
if(flag==true){
    pick=0;
}https://stackoverflow.com/questions/22469792
复制相似问题