提问人:Hail_World 提问时间:11/6/2023 最后编辑:Roman CHail_World 更新时间:11/7/2023 访问量:46
输出的方法和问题
Methods and problems with output
问:
我正在尝试学习 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
答:
1赞
Roman C
11/6/2023
#1
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());
}
0赞
Reilas
11/7/2023
#2
"...这个代码有什么问题,为什么我不能打印任何东西?..."
您的声明不正确。
CarLoan masterTask = new masterTask();
而是创建一个新的“CarLoan”。
CarLoan masterTask = new CarLoan();
此外,将 masterTask 发送到 println,而不是 CarLoan。
System.out.println(masterTask);
评论
main
CarLoan
masterTask
CarLoan
System.out.println(new CarLoan());
CarLoan masterTask = new CarLoan(); System.out.println(masterTask);
CarLoan masterTask;
masterTask
new CarLoan()
=
masterTask
.
masterTask