How can I get 2 print data in a method?
On this below, it looks my coding writing that should not need to write twice. In the same function want to put into one writing of coding only.
public class StringBuffer{
public static void main(String[] args) {
countTo_N_Improved();
System.out.println();
Reverse();
}
private final static int MAX_LENGTH = 24;
private final static int MAX_LENGTH1 = 24;
private static String buffer = "";
private static String buffer1 = "";
private static void emit(String nextChunk) {
if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
System.out.println(buffer);
buffer = "";
}
if (nextChunk.length()==2){
nextChunk = " 0"+nextChunk.trim();
}
buffer += nextChunk;
}
private static void emit1(String nextChunk1) {
if(buffer1.length() + nextChunk1.length() > MAX_LENGTH1) {
System.out.println(buffer1);
buffer1 = "";
}
if (nextChunk1.length()==2){
nextChunk1 = " 0"+nextChunk1.trim();
}
buffer1 = nextChunk1+buffer1;
}
private static final int N = 100;
private static void countTo_N_Improved() {
for (int count=2; count<=N; count=count+2) {
emit(" " + count);
}
}
private static void Reverse() {
for (int count1=2; count1<=N; count1=count1+2) {
emit1(" " + count1);
}
}
}
The output must be:
02 04 06 08 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 84 86 88 90 92 94 96
16 14 12 10 08 06 04 02
32 30 28 26 24 22 20 18
48 46 44 42 40 38 36 34
64 62 60 58 56 54 52 50
80 78 76 74 72 70 68 66
96 94 92 90 88 86 84 82
First for the real data Max_Length and the second for reverses.
You can indeed refactor both countToN and emit to a single function with the parameter reverse:
public class StringBuffer {
private final static int MAX_LENGTH = 24;
private static final int N = 100;
private static String buffer = "";
public static void main(String[] args) {
countToN(false);
System.out.println();
countToN(true);
}
private static void countToN(boolean reverse) {
for (int count = 2; count <= N; count = count + 2) {
emit(" " + count, reverse);
}
buffer = "";
}
private static void emit(String nextChunk, boolean reverse) {
if (buffer.length() + nextChunk.length() > MAX_LENGTH) {
System.out.println(buffer);
buffer = "";
}
if (nextChunk.length() == 2) {
nextChunk = " 0" + nextChunk.trim();
}
buffer = (reverse ? nextChunk + buffer : buffer + nextChunk);
}
}