如何将输入字符串的每个单词设置在新行上并将输出放置在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”,则只有一个“ |”添加到第一行和最后一行。
关于如何实现此目标的任何建议?
答案 0 :(得分:2)
将通话更改为printBox
。当前,您传递了一个名为String
的{{1}},而是通过在空间上分割行来传递line
(s)的数组。喜欢,
String
仅此更改,当我输入“ Hello world Goodbye world”时,我得到
printBox(line.split(" "));
答案 1 :(得分:1)
printBox函数仅接收一个包含全部文本的字符串,而不是预期的数组。您可以更改它以接收一个数组,并拆分接收到的文本以传递给该函数,如下所示:
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.split(" "));
}
// 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);
}
}
结果将是这样的:
Enter a line of text: test longertest
+------------+
| test |
| longertest |
+------------+