有人可以帮我纠正我的代码吗?它被创建用于计算住房贷款(UMI),编码是正确的,但它没有完全显示输出。在“输入贷款期限”后,它显示一个框。还有另一种方法来设置class Variables
中的变量吗?
package assignment.pkg2;
import java.util.Scanner;//for Scanner
import java.text.DecimalFormat;//for using decimal format
class Variables{ //set the variables
private double p, r, n;
public void setVarP (double amount){
this.p = amount;
}
public void setVarR (double rate){
this.r = rate;
}
public void setVarN (int duration){
this.n = duration;
}
public double getVarP(){
return p;
}
public double getVarR(){
return r;
}
public double getVarN(){
return n;
}
}
class EMIcalc{ //the calculating part
private double monthlyPay, pow;
Variables var = new Variables();
Scanner scanner = new Scanner(System.in);
public void getPay(){
pow = Math.pow (1+(var.getVarR()/12), - var.getVarN());
monthlyPay = var.getVarP() * ( (var.getVarR()/12) / (1 - pow) );
DecimalFormat Dformat = new DecimalFormat("##.##");
System.out.println(Dformat.format(monthlyPay));
}
}
public class Assignment2 {
public static void main(String[] args) {
Variables var1 = new Variables();
EMIcalc calc = new EMIcalc();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your loan amount");
var1.setVarP(scanner.nextDouble());
System.out.println("Enter interest rate");
var1.setVarR(scanner.nextDouble());
System.out.println("Enter loan duration");
var1.setVarN(scanner.nextInt());
calc.getPay();
}
}
答案 0 :(得分:0)
您正在将值设置为var1
,但calc
会查看其内部var
字段,该字段是另一个对象。您只需将var1.set...
替换为calc.var.set...
。
或者您可以将Variables
和EMIcalc
类合并为一个。
答案 1 :(得分:-1)
你在找这个吗?
import java.text.DecimalFormat;
import java.util.Scanner;
class Variables { //set the variables
private double p, r, n;
public double getVarP() {
return p;
}
public void setVarP(double amount) {
this.p = amount;
}
public double getVarR() {
return r;
}
public void setVarR(double rate) {
this.r = rate;
}
public double getVarN() {
return n;
}
public void setVarN(int duration) {
this.n = duration;
}
}
class EMIcalc { //the calculating part
Variables var = new Variables();
Scanner scanner = new Scanner(System.in);
private double monthlyPay, pow;
public void getPay() {
pow = Math.pow(1 + (var.getVarR() / 12), -var.getVarN());
monthlyPay = var.getVarP() * ((var.getVarR() / 12) / (1 - pow));
DecimalFormat Dformat = new DecimalFormat("##.##");
System.out.println(Dformat.format(monthlyPay));
}
}
public class Assignment2 {
public static void main(String[] args) {
EMIcalc calc = new EMIcalc();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your loan amount");
calc.var.setVarP(scanner.nextDouble());
System.out.println("Enter interest rate");
calc.var.setVarR(scanner.nextDouble());
System.out.println("Enter loan duration");
calc.var.setVarN(scanner.nextInt());
calc.getPay();
}
}
PS:自己尝试分配。