public class Format {
public static void main(String [] args) {
String s1 = "ICS";
String s2 = "Computing";
String s3 = "PE";
String s4 = "Sport";
String s5 = "ENGL";
String s6 = "Language";
// Print above strings in a tabular format
}
}
完成上面的Java程序,使其完全按照下表所示打印这些字符串,使每个条目精确地从上一行中的一列开始:
First Name Last Name
=======================
ICS Computing
PE Sport
ENGL Language
注意:您的程序应该适用于任何字符串集,而不仅仅是练习中给定的字符串。
答案 0 :(得分:3)
您必须格式化适当的字符串
这可以帮到你:
String s1 = "ICS";
String s2 = "Computing";
...
String format = "%1$-14s%2$-9s\n";
System.out.format(format, "First Name", "Last Name");
System.out.println("=======================");
System.out.format(format, s1, s2);
System.out.format(format, s3, s4);
System.out.format(format, s5, s6);
然后输出正是您所需要的。但是如果你需要一些动态版本,你需要按照你的方式计算“14”和“9”。
如果您想了解如何格式化String,请查看this教程。它包含类似的格式,并在将来通过类似练习帮助您
答案 1 :(得分:2)
您应该做的第一件事是计算第一列所需的大小。这是四个值中的最大值:
s1
。s3
。s5
。可以使用当前的伪代码计算:
c1len = length ("First Name")
if length (s1) > c1len:
c1len = length (s1)
if length (s3) > c1len:
c1len = length (s3)
if length (s5) > c1len:
c1len = length (s5)
一旦你有了这个,就可以根据这个长度格式化相关的字符串了。
这基本上是:
output "First Name" formatted to length c1len
output " Last Name" followed by newline
for i = 1 to c1len:
output "="
output "===========" followed by newline.
output s1 formatted to length c1len
output " "
output s2 followed by newline
output s3 formatted to length c1len
output " "
output s4 followed by newline
output s5 formatted to length c1len
output " "
output s6 followed by newline
您应该查看String课程,特别是length()
和format()
,System.out.print
和System.out.println
。
答案 2 :(得分:0)
看看System.out.println()
答案 3 :(得分:0)
public class Format {
public static void main(String [] args) {
String s1 = "ICS";
String s2 = "Computing";
String s3 = "PE";
String s4 = "Sport";
String s5 = "ENGL";
String s6 = "Language";
String sep= " ";
// Print above strings in a tabular format
System.out.println(s1 + sep.substring(s1.length()) + s2);
System.out.println(s3 + sep.substring(s3.length()) + s4);
System.out.println(s5 + sep.substring(s5.length()) + s6);
}
}