【问题标题】:How to use an output from an array and then sum all of its number in Java?如何使用数组的输出,然后在 Java 中将其所有数字相加?
【发布时间】:2018-08-25 02:18:43
【问题描述】:

我希望代码从数组中获取数据,然后显示其中的数字之和,但我碰壁了。

public class StringBuffer{
public static void main(String[] args) {
  countTo_N_Improved();
}
   private final static int MAX_LENGTH=30;
   private static String buffer = "";
   private static void emit(String nextChunk) {
        if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
        System.out.println(buffer);
        buffer = "";  
   }
   buffer += nextChunk;
 }
  private static final int N=100;
  private static void countTo_N_Improved() {
  for (int count=2; count<=N; count=count+2) {
     emit(" " + count);
     }
  }
}

这是输出

 2 4 6 8 10 12 14 16 18 20 22
24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82

我希望输出变成这样

 2 4 6 8 10 12 14 16 18 20 22
24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82

And the sum of the number from the array is 1722

非常感谢。

【问题讨论】:

    标签: arrays stringbuffer emit


    【解决方案1】:

    希望这个回答对你有帮助

    public class StringBuffer{
    int sum = 0;
    public static void main(String[] args) {
      countTo_N_Improved();
    }
       private final static int MAX_LENGTH=30;
       private static String buffer = "";
       private static void emit(String nextChunk, int count) {
            if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
            sum += count;
            System.out.println(buffer);
            buffer = "";  
       }
       buffer += nextChunk;
     }
      private static final int N=100;
      private static void countTo_N_Improved() {
    
      for (int count=2; count<=N; count=count+2) {
         emit((" " + count),count);
         }
      }
      System.out.println("And the sum of the number from the array is "+sum);
    }
    

    【讨论】:

    • 很抱歉,您的脚本仅从 2 + 4 + .... + 100 开始计算,因此结果将始终为 2550。而我被要求的脚本必须从 2 + 4 + 开始计算... + 所以结果取决于最后一个数字。无论如何,感谢您的回答,它确实让人眼前一亮。
    • 你检查了吗?
    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 2018-03-28
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多