0

I want the code to take the data from the array and then show the sum of the number from it, but I hit the wall.

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);
     }
  }
}

and this is the output

 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

I want the output to become like this

 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

Many thanks.

1 Answers1

0

I hope this answer will be helpful for you

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);
}
NIKHIL NEDIYODATH
  • 2,703
  • 5
  • 24
  • 30
  • I am sorry but your script just counting from 2 + 4 + .... + 100 so the result will always be 2550. While the script that I am asked have to count from 2 + 4 + ... + __ so the result is depends on the last number. Anyway thanks for the answer it really sheds a light. – Seto Mulyadi Mar 16 '18 at 07:00
  • Did you check it? – NIKHIL NEDIYODATH Mar 19 '18 at 05:49