打印出分配给单个变量的多个值

时间:2019-02-04 04:47:06

标签: java

我有一个for循环,该循环将一直持续到我不小于代码中所示的maxnum为止。在此期间,它将进行模运算,我正在尝试为可分配的变量累积尽可能多的值。我的问题是在代码中,它仅执行单个操作,而不会继续执行该操作,而是为其分配了多个值。我应该改变循环吗?

尝试分配数组列表 i ++低于

 for(int i =1; i < maxnum; i++ ) {
    MulT = i % divisor;

    }

 if ( MulT==0 ) {

        System.out.println("Multiples of " + dividend+ " between 1 and "+ maxnum +" is");
        System.out.println(MulT);

    } 
else {
      System.out.println("Multiples of " + dividend +  " between 1 and " + maxnum+ "are:");
       System.out.print("No numbers were found");
   }

1到10之间的2的倍数是:

2 4 6 8 10

1 个答案:

答案 0 :(得分:1)

如果要获取存储在变量中的所有值,则必须在控制台中打印该变量后在for循环中迭代该变量,请检查以下代码。

  int maxnum=10;
  int divisor=2;
  int  val[] = new int[maxnum];
  int j=0;

  for(int i =1; i <= maxnum; i++ ) {
    double MulT = i % divisor;          
        if(MulT==0){            
            val[j]=i;
            j++;
        }
  }
  if(val[0] > 0){
      System.out.print("Multiples of " + divisor+ " between 1 and "+ maxnum +" is:");
      for(int k=0;k < val.length;k++){
          if(val[k]!=0){
              System.out.print(" "+val[k]);
          }
      }
  }else{
      System.out.println("Multiples of " + divisor +  " between 1 and " + maxnum+" are:");
      System.out.print("No numbers were found");
  }