我正在尝试学习Java技术。
这段代码有什么问题,为什么我不能打印任何东西?
public class CarLoan {
int carLoan = 10000;
int loanLenght = 3; //This will represent a loan length of 3 years.
int interestRate = 5; //This will represent an interest rate of 5% on the loan
int downPayment = 2000; //This will represent the down payment provided by a user for this car purchase.
public CarLoan() {
if (loanLenght <= 0 && interestRate <=0) {
System.out.println("Error! You must take out a valid car loan");
} else if (downPayment >= carLoan){
System.out.println("The car can be paid in full");
}else{
int remainingBalance = carLoan - downPayment;
int months = loanLenght * 12;
int monthlyBalance = remainingBalance / months;
System.out.println("false");
}
}
public static void main(String[] args) {
CarLoan masterTask = new masterTask();
System.out.println(CarLoan);
}
}
我尝试更改方法,使其
void
并在其中列出变量。
masterTask
是CarLoan
类型的变量。当您尝试创建 CarLoan
的实例时,您在语句中误用了它。
public static void main(String[] args) {
CarLoan masterTask = new CarLoan();
System.out.println(masterTask);
}
然后你应该创建一个方法
toString()
来打印对象。
你也误解了Java中构造函数的用途。它不用于进行计算。如果你想让一个对象做某事,那么你应该创建一个方法,然后在创建该对象的实例时调用这个方法。变量将对象的实例作为引用,并可用于调用该对象的方法。
public String makeCarLoan() {
String result;
if (loanLenght <= 0 && interestRate <=0) {
result = "Error! You must take out a valid car loan";
} else if (downPayment >= carLoan){
result = "The car can be paid in full";
}else{
int remainingBalance = carLoan - downPayment;
int months = loanLenght * 12;
int monthlyBalance = remainingBalance / months;
result = "false";
}
return result;
}
然后就可以重写之前的代码了
public static void main(String[] args) {
CarLoan carLoan = new CarLoan();
System.out.println(carLoan.makeCarLoan());
}
“...这段代码有什么问题,为什么我不能打印任何东西?...”
您的声明不正确。
CarLoan masterTask = new masterTask();
创建一个新“汽车贷款”。
CarLoan masterTask = new CarLoan();
此外,将 masterTask 发送到 println,而不是 CarLoan。
System.out.println(masterTask);