1.方法
方法名不能以数字开头
” ctrl + alt + L 自 动 整 理 代 码 “
出现错误可以用
throw new illegaArgumentExecption(" 这里写返回错误的提示信息")
throw new 异常类型 (“刚刚写的是非法参数异常”)
也可以用 while 限制条件来避免用户输入错误
用方法写出还款程序
package javaBaica;
import java.text.NumberFormat;
import java.util.Scanner;
public class daikuan {
public static void main(String[] args) {
double p = inputp();
int m = inputm();
double mr = inputmr();
double payment = daikuan.jisuan(p, mr, m);
daikuan.xiangq(p, mr, m, payment);
}
static void xiangq(double p, double mr, int m, double payment) {
for (int i = 0; i < m; i++) {
double payinter = p * mr;
double payprincipal = payment - payinter;
p -= payprincipal;
System.out.print("月份:" + (i + 1));
System.out.print("\t还款总额" + NumberFormat.getCompactNumberInstance().format(payment));
System.out.print("\t偿还本金" + NumberFormat.getCompactNumberInstance().format(payprincipal));
System.out.print("\t偿还利息" + NumberFormat.getCompactNumberInstance().format(payinter));
System.out.println("\t剩余本金" + NumberFormat.getCompactNumberInstance().format(p));
}
System.out.println("总额" + payment * m);
}
/**
* 计算等额本息的
*
* @param p 本金
* @param mr 月利率
* @param m 月数
* @return 还款的金额
*/
static double jisuan(double p, double mr, int m) {
double pow = Math.pow(1 + mr, m);
return p * mr * pow / (pow - 1);
}
/**
* @return 用户
*/
static double inputp() {
Scanner scanner = new Scanner(System.in);
//
System.out.println("请输入本金");
double p = scanner.nextDouble();
//
if (p < 0) {
throw new IllegalArgumentException("本金必须大于0");
}
return p;
}
//输入换年利率
static double inputmr() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年利率");
double yr = scanner.nextDouble();
if (!(yr > 1) || !(yr < 36)) {
throw new IllegalArgumentException("年利率有问题小心被骗");
}
double mr = yr / 12 / 100;
return mr;
}
//输入还款月数
static int inputm() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入还款月数");
int m = scanner.nextInt();
if (m < 1 || m > 360) {
throw new IllegalArgumentException("你打算还多久想清楚再填");
}
return m;
}
}