你如何格式化输出?
我的代码是:
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
int cuToComp;
int cuPerTerm;
public static void main(String[] args) {
final double COST = 2890.00; //flat-rate tuition rate charged per term
final int MONPERTERM = 6; //number of months per term
int cuToCompTotal = 0;
int numTerm;
int numMonToComp;
double tuition;
//prompt for user to input the number of CUs for each individual course remaining.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
//add all CUs from individual courses to find the Total number of CUs left to complete.
while (cuToComp > 0)
{
cuToCompTotal += cuToComp;
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
cuToComp = in.nextInt();
}
System.out.println("The total number of CUs left is " + cuToCompTotal);
//prompt for user to input how many CUs they plan to take per term.
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm < 12) //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
{
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
while(cuPerTerm < 12){
System.out.print("How many credit units do you intend to take per term? ");
cuPerTerm = in.nextInt();
}
}
//Calculate the number of terms remaining, if a remain is present increase number of terms by 1.
numTerm = cuToCompTotal/cuPerTerm;
if (cuToCompTotal%cuPerTerm > 0)
{
numTerm = numTerm + 1;
}
System.out.println("The Number of Terms you have left is " + numTerm + " Terms. ");
//Calculate the number of Months left to complete
numMonToComp = numTerm * MONPERTERM;
System.out.println("Which is " + numMonToComp + " Months. ");
//calculate the tuition cost based on the number of terms left to complete.
tuition = numTerm * COST;
System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");
}
}
最后一行 System.out.println("你的总学费是:" + "$" + 学费 +" . ");
我需要对其进行格式化,使其具有两位小数(amount.00)以及占位符的逗号。
我试过了
System.out.printf("Your Total Tuition Cost is: " + "$%.2f" + tuition +" . ");
但是我得到一个错误!!!!
所以我加了
NumberFormat my = NumberFormat.getInstance(Locale.US);
my.setMaximumFractionDigits(2);
my.setMinimumFractionDigits(2);
String str = my.format(tuition);
System.out.printf("Your Total Tuition Cost is: $", (NumberFormat.getInstance(Locale.US).format(tuition)));
哪个输出
Your Total Tuition Cost is: $BUILD SUCCESSFUL (total time: 13 seconds)
我的错误是什么???
也永远不会有十进制值,xx.00 将永远是 .00(这有关系吗?)