I have an application where I need to highlight some information that is printed to the console, so I wrote some static library methods which do that. I tested for bugs. Is my code clean and satisfying, or are there aspects to criticise?
It has to work for multiple lines - given as a string that contains newlines and for arrays and lists.
- Compile with: javac *.java
- Run with: Main.java
Example Output
+---------------------------+
| one |
| two three |
| four |
| let your dreams come true |
| nothing is impossible |
+---------------------------+
+--------+
| Single |
+--------+
Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String string = "one\ntwo three\nfour\nlet your dreams come true\n";
string += "nothing is impossible";
System.out.println(makeBorderString(string));
System.out.println(makeBorderString("Single"));
}
// frames a string that contains newlines
// does not work for strings that contain symbols that need more than one
// space unit, for example tabs
public static String makeBorderString(String value) {
String[] lines = value.split("\\r?\\n");
return makeBorderStringFromArray(lines);
}
// does not work for strings that contain symbols that need more than one
// space unit, for example tabs
public static String makeBorderStringFromArray(String stringArray[]) {
List<String> stringList = Arrays.asList(stringArray);
return makeBorderStringFromList(stringList);
}
// does not work for strings that contain symbols that need more than one
// space unit, for example tabs
public static String makeBorderStringFromList(List<String> stringList) {
// find most long line
int mostLong = 0;
for (int i = 0; i < stringList.size(); i++) {
if (stringList.get(i).length() > mostLong) {
mostLong = stringList.get(i).length();
}
}
StringBuilder sb = new StringBuilder();
// make upper Border border
sb.append("+" + repeatSymbol('-', mostLong + 2) + "+\n");
// make body
for (int i = 0; i < stringList.size(); i++) {
String current = stringList.get(i);
int whiteSpaceAmount = mostLong - current.length();
if (whiteSpaceAmount > 0) {
String whitespace = repeatSymbol(' ', + whiteSpaceAmount);
sb.append("| " + current + whitespace + " |\n");
} else {
sb.append("| " + current + " |\n");
}
}
// make lower Border border
sb.append("+" + repeatSymbol('-', mostLong + 2) + "+");
return sb.toString();
}
public static String repeatSymbol(char symbol, int times) {
if (times > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++) {
sb.append(symbol);
}
return sb.toString();
}
return null;
}
}