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
}
}
Complete above Java program such that it prints these strings exactly as shown in the following table, having each entry starting precisely at the same column of the one in the previous row:
First Name Last Name
==================开发者_高级运维=====
ICS Computing
PE Sport
ENGL Language
NOTE: Your program should work for any set of strings, NOT ONLY the given ones in the exercise.
You must format String appropriate
This can help you:
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);
then output is exactly what you need. But if you need some dynamic version you need just count "14" and "9" in your way.
If you want learn how you can format String look at this tutorial. It contains similar formatting and help you in the future with similar exercises
The first thing you should do is work out the size required for the first column. This is the maximum of the four values:
- 10, the size of "First Name".
- the size of
s1
. - the size of
s3
. - the size of
s5
.
That can be calculated with the current pseudo-code:
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)
Once you have that, it's a simple matter of formatting the relevant strings based on that length.
This is basically:
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
You should look into the String class, specifically length()
and format()
, System.out.print
and System.out.println
.
Take a look at System.out.println()
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);
}
}
精彩评论