正如我们所知,我们可以在格式化打印中打印时确定对齐和小数点数,例如:
System.out.printf( "%9.2f", total );
System.out.printf( "%-20s", name );
System.out.printf( "%8s", adress );
但我如何才能使它成为字符串表示? 此代码显示在操作期间给予患者的药物剂量表,我使用joptionpane.showMessageDialog打印出字符串表示并且无法修复对齐问题,这是代码:
public class DrugsTable
{
private String patientName; // name of the patient
private int doses[][]; // two-dimensional array of patient doses
private String opDrugs []={"O2","N2O","gas","musle
relaxent","narcotic","fluid","atropine","neostagmine"};
String str = "";
// two-argument constructor initializes patientName and doses array
public DrugsTable( String name, int dosesArray[][] )
{
patientName = name; // initialize patientName
doses = dosesArray; // store doses
} // end two-argument DrugsTable constructor
// method to set the patient name
public void setPatientName( String name )
{
patientName = name; // store the course name
} // end method setPatientName
// method to retrieve the patient name
public String getPatientName()
{
return patientName;
} // end method getPatientName
// display a welcome message to the user
public void displayMessage()
{
// getpatientName gets the name of the course
str +="Welcome;\n"+getPatientName()+"\n\n";
} // end method displayMessage
// perform various operations on the data
public void processDoses()
{
// output doses array
outputdoses();
} // end method processdoses
// determine Total dose given during operation
public double getTotal( int setOfdoses[] )
{
int total = 0; // initialize total
// sum doses for one drug
for ( int dose1 : setOfdoses )
total += dose1;
// return total of doses
return (double)total ;
} // end method getTotal
// output the contents of the doses array
public void outputdoses()
{
str+=" "; // align column heads
// create a column heading for each time
str +="\t"+"Time1 "+"Time2 "+"Time3";
str+=" Total\n"; // total dose column heading
// create rows/columns of text representing array doses
for ( int drug = 0; drug < doses.length; drug++ )
{
str +=opDrugs[drug]; //getText
for ( int dose : doses[ drug ] ) // output patient's doses
str +=" "+String.valueOf(dose);
// call method getTotal to calculate drug's total dose;
// pass row of doses as the argument to getTotal
double total = getTotal( doses[ drug ] );
str +=" "+String.valueOf(total)+"\n";
} // end outer for
} // end method outputdoses
} // end class DrugsTable
这是主要方法:
import javax.swing.JOptionPane;
public class DrugsTableTest
{
public static void main( String args[] )
{
// two-dimensional array of drugs doses given during operation
int drugDosesArray[][] = { { 99, 96, 70 },
{ 68, 87, 90 },
{ 94, 100, 90 },
{ 100, 81, 82 },
{ 83, 65, 85 },
{ 78, 87, 65 },
{ 85, 75, 83 },
{ 91, 94, 100 }};
DrugsTable drugsTable = new DrugsTable(
"drugs given during operation are:", drugDosesArray );
drugsTable.displayMessage();
drugsTable.processDoses();
JOptionPane.showMessageDialog(null,drugsTable.str);
} // end main
} // end class DrugsTableTest