這是一項家庭作業,我正在設計一個興趣計算器。我需要使用BigDecimal類,但無法弄清楚如何以貨幣或百分比形式輸出。我不完全確定要問什麼問題,但我要發佈兩個代碼BigDecimal類代碼,另一個以我需要的方式顯示輸出,但不使用BigDecimal。任何建議感激。Java Bigdecimal類
import java.util.Scanner;
import java.math.*;
public class project3a
{
public static void main(String[] args)
{
System.out.println("Welcome to the interest calculator");
System.out.println();
// create a scanner object and start while loop
Scanner sc = new Scanner(System.in);
String choice ="y";
while (choice.equalsIgnoreCase("y"))
{
//Get input from user
System.out.print("Enter Loan amount: ");
double Loanamount = sc.nextDouble();
System.out.print("Enter Interest Rate: ");
double interestrate = sc.nextDouble();
//calculate results
double Interest = Loanamount * interestrate;
//format
BigDecimal decimalLoanamount = new BigDecimal(Double.toString (Loanamount));
decimalLoanamount = decimalLoanamount.setScale(2, RoundingMode.HALF_UP);
BigDecimal decimalinterestrate = new BigDecimal(Double.toString(interestrate));
BigDecimal decimalInterest = new BigDecimal (Double.toString(Interest));
decimalInterest = decimalInterest.setScale(2,RoundingMode.HALF_UP);
//Display results
System.out.println("Loan amount: " + decimalLoanamount);
System.out.println("Interest rate: " + decimalinterestrate);
System.out.println("Interest:" + decimalInterest);
System.out.println();
//see if user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
import java.util.Scanner;
import java.text.NumberFormat;
import java.math.*;
public class project3a
{
public static void main(String[] args)
{
System.out.println("Welcome to the interest calculator");
System.out.println();
// create a scanner object and start while loop
Scanner sc = new Scanner(System.in);
String choice ="y";
while (choice.equalsIgnoreCase("y"))
{
//Get input from user
System.out.print("Enter Loan amount: ");
double Loanamount = sc.nextDouble();
System.out.print("Enter Interest Rate: ");
double interestrate = sc.nextDouble();
//calculate results
double Interest = Loanamount * interestrate;
//format and display results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
String message =
"Loan amount: " + currency.format (Loanamount) + "\n"
+ "Interest rate: " + percent.format (interestrate)+ "\n"
+ "Interest: " + currency.format (Interest) + "\n";
System.out.println(message);
//see if user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
代碼越少,問題越好,答案越快越好。 – 2012-02-10 02:40:07
我只是試圖表明,我正在努力,而不是隻是爲了尋找答案,因爲這是作業。 – 2012-02-10 02:52:01
您能更具體地瞭解您期望的輸出和您獲得什麼? 'currency.format()'和'percent.format()'是你的問題嗎? – 2012-02-10 02:58:02