unable to format output
System.out.println("Name\tRollno\tAddress\tPercen开发者_JAVA百科tage");
while(rs.next())
{
name=rs.getString(1);
lname=rs.getString(2);
address=rs.getString(3);
city=rs.getString(4);
System.out.print(name+"\t\t");
if(lname.length()<=7)
{
System.out.print(lname+"\t\t");
}
else
System.out.print(lname+"\t");
if(address.length()<=7)
{
System.out.print(address+"\t\t");
}
else
System.out.print(address+"\t");
System.out.println(city);
}
The data is not coming under the heading name address etc. How to format it the output? Can anyone help me?
I would advise using the String.format
method with %15s
where 15 is the width of the column and can be anything you like.
Using "\t"
is pretty dependent on how you're displaying the result, e.g. in a text editor, the width of a tab character can be anything the user chooses.
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29
Although String.format would work perfectly, I'd venture towards PrintStream.printf(). The following code would print out what you want in perfect columns. Depending on the actual values you have in your result set, you might need to change the value for the width of the columns
int nameWidth = 15
int rollNumberWidth = 10
int adddressWidth = 25
int percentWidth = 5
String format = "%" + nameWidth + "s"
+ "%" + rollNumberWidth + "s"
+ "%" + addressWidth + "s"
+ "%" + percentWidth + "s\n";
System.out.printf(format ,"Name", "Rollno", "Address", "Percentage");
while(rs.next())
{
name = rs.getString(1);
lname = rs.getString(2);
address = rs.getString(3);
city = rs.getString(4);
System.out.printf(format , name, lname, address, city);
}
精彩评论