【问题标题】:Print out the numbers from the for loop打印出 for 循环中的数字
【发布时间】:2020-09-24 01:14:20
【问题描述】:

返回类型为 void

无输入参数

打印出数字计算结果,用空格隔开,用当前数字加上从0到(a+b)的下一个数字。

例如,如果 for 循环的数字是 0、1、2、3、4、5、6,那么它将添加 0+1、1+2、2+3、3+4、4+ 5, 5+6 并像 0,1,2,3,4,5,6 一样打印出这些值。

老实说,我不知道如何做到这一点,所以我不会撒谎,所以有人可以帮我编写代码并解释或只是帮助我。

public class ForFogMe
{
   public int a, b;
   public String str;

    public void addUp(){  
       
     for(a = 0; a <= 6; a ++){
         System.out.print(a);        
        }
       
       String s = Integer.toString(a);
       System.out.println();
       System.out.print(s.substring(0,2) );
       
    }
   
   public static void main(String args[]){
        
       ForFogMe me = new ForFogMe();
       me.addUp();
    }
}

【问题讨论】:

    标签: java for-loop substring


    【解决方案1】:

    如果您只想打印从 0 到 6 的数字的总和,您可以这样做:

    public void addUp() {
       for(a = 0; a < 6; a++) {
           System.out.print(a+(a+1) + ",");
       }
       System.out.print("\b"); // to delete last comma
    }
    

    在第一次迭代中 a0 a+11 所以你打印它们的总和就像 (a+(a+1) + ",") 输出 "1,"。它会重复直到到达6。最后我们有1,3,5,7,9,11, 所以我用System.out.print("\b"); 删除最后一个字符,所以我们得到1,3,5,7,9,11

    【讨论】:

      【解决方案2】:

      我相信这应该可以解决问题:

      public static void addUp(){
          final int[] array = {0,1,2,3,4,5,6};
          int[] result = new int[array.length-1];
          for(int i = 0; i < array.length-1; i++) {
              result[i]=array[i]+array[i+1];
          }
          result[3]=array[array.length-1];
          for(int i = 0; i < result.length; i++) {
              System.out.print(result[i]+" ");
          }
          
      
            
         }
      

      测试用例(数组):

      0,1,2,3,4,5,6
      

      输出:

      1 3 5 6 9 11 
      

      注意:数组大小无关紧要。

      【讨论】:

      • 对不起,我可能说错了,但需要有一个 6 我的意思是说它就像最大的六个,所以数字是 0,1,2,3,4,5,6
      • 是的,但是如果测试用例是 0,1,2,3,4,5,6 并且您必须执行 0+1、1+2、2+3、3+4 , 4+5, 5+6 表示输出应该是 1,3,5,7,9,11 而不是 1,5,9,6
      • 这很好用,但是如果没有最终的 int[] 数组作为参数,我该怎么做呢?
      • @Vobacocm 我已经为您完成了。这有帮助吗?如果是,请考虑投票!
      • @Vobacocm 很高兴为您提供帮助 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2021-03-06
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多