呵呵最近好久没写日记了学java感觉也有一点体会我可能是新手用DOS命令下执行的吧发现写程序还是有很多错误令人郁闷的是那些错误我死活都检查不出来呵呵今天总算是调试成功了吧还算比较高兴给大家看看这段代码顺便解释一下代码的意思我是新手说的不对的西方希望大家给多多指点。
【简介】这个是计算一个贷款支付额的程序,本程序要求用户输入利率,年数和贷款的总额,程序计算月支付金额和总偿还金额,能够算出月支付额。下面是编写程序的步骤:
1.提示用户输入年利率,年数和贷款的总额
2.利用年利率算出月利率
3.通过前面的公式计算月支付额
4.计算总支付额,他是月支付额乘以12再乘以年数,
5在消息对话框中显示月支付额
import javax.swing.JOptionPane;
public class ComputeLoan {
/*Main method*/
public static void main(String[] args){
//Enter yearly interest rate
String annualInterestRateString =JOptionPane.showInputDialog(
"Enter yearly interest rate, for example 8.25:");
//Convert string to double
double annualInterestRate =
Double.parseDouble (annualInterestRateString);
//Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
//Enter number of years
String numberOfYearsString = JOptionPane.showInputDialog(
"Enter number of years as an interger, \nfor example S:");
//Convert string to int
int numberOfYears = Integer.parseInt(numberOfYearsString);
//Enter loan amount
String loanString = JOptionPane.showInputDialog(
"Enter loan amount,for example 120000.95:");
//Convert String to double
double loanAmount = Double.parseDouble(loanString);
//Calculate payment
double monthlyPayment = loanAmount * monthlyInterestRate / (
1-1 / Math.pow(1+ monthlyInterestRate,numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Format to keep two digits after the decimal point
monthlyPayment = (int)(monthlyPayment * 100) /100.0;
totalPayment = (int)(totalPayment * 100) / 100.0;
//Display results
String output = "The monthly payment is" +monthlyPayment +
"\nThe total payment is" + totalPayment;
JOptionPane.showMessageDialog(null,output);
}
}
其中showInputDialog显示一个输入对话框。输入双精度值的利率,然后点击OK接受该输入。该值以字符串的形式返回,赋值给String变量annualInterestRateString。Double.parseDouble(annualInterestRateString)该字符串转换为一个double值。如果输入的不对的不是数值,就会出现运行时的错误。到时候可能等我学到了处理异常的时候能够让程序继续执行吧。
方法中的每个新变量必须声明且只能声明一次,要为变量选择最正确的数据类型。例如,尽管可以将numberOfYears声明为long、float或者是double型,但是最好声明为Int 注意,numberOfYears可能最适合的类型是byte。然而,为了简便起见,用int表示整型 double表示浮点型
<注意>如果在对话框中点击 cancel,无字符串返回,系统出现运行时错误