如何将输入字符串的每个单词设置为新行并将输出放置在 ASCII 框中?
我有以下代码:
import java.util.Scanner;
public class labSix {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a line of text: ");
String line = in.nextLine();
printBox(line);
}
// Returns the length of the longest token in the line.
private static int getMaxLength(String... strings) {
int len = Integer.MIN_VALUE;
for (String str : strings) {
len = Math.max(str.length(), len);
}
return len;
}
// Pad the strings with spaces.
private static String padString(String str, int len) {
StringBuilder sb = new StringBuilder(str);
return sb.append(fill(' ', len - str.length())).toString();
}
// Fill the string to the amount determined in padString.
private static String fill(char ch, int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.append(ch);
}
return sb.toString();
}
// Print the box
public static void printBox(String... strings) {
int maxBoxWidth = getMaxLength(strings);
String line = "+" + fill('-', maxBoxWidth + 2) + "+";
System.out.println(line);
for (String str : strings) {
System.out.printf("| %s |%n", padString(str, maxBoxWidth));
}
System.out.println(line);
}
}
如果我尝试分割字符串并将“”替换为“\n”,那么只有一个“|”添加到第一行和最后一行。
关于如何实现这一目标有什么建议吗?
最佳答案
将您的调用更改为 printBox
。您当前传递一个名为 line
的 String
,而是通过在空间上分割行来传递一个 String
数组。就像,
printBox(line.split(" "));
经过这样的更改,当我输入“Hello world Goodbye world”时,我得到了
+---------+
| Hello |
| world |
| Goodbye |
| world |
+---------+
关于java - 如何将每个单词另起一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52694086/