我应该制作一个班级和一个测试员班级,允许客户输入他的名字和当前金额,以及他想要的任何存款或取款。可能有不正确的代码,但我想知道我在代码中做错了什么。其中一个问题是它说getBalance是一个无效的方法声明。
这是带有构造函数的类
public class BankAccount{
public String name;
public double Balance, Withdrawal, Deposit;
public BankAccount(double bal, String nm){
name = nm;
Balance = bal;
}
public void setName (String nm){
name = nm;
}
public String getName(){
return name;
}
public String toString(){
return "Name: " + name + "\n" +
"New Balance : " + getBalance;
}
public getBalance(){
return Balance;
}
public double Withdrawal(){
bal = Balance - Withdrawal;
}
public double Deposit(){
bal = Balance + Deposit;
}
}
这是测试人员类
import java.util.Scanner;
public class BankAccountTester{
public static void main(String [] args){
Scanner reader = new Scanner(System.in);
a1 = new BankAccount();
String name;
int Balance, Withdrawal, Deposit;
System.out.println("What is the name of the bank account holder?");
name = reader.nextLine();
System.out.println("What is your current balance?");
Balance = reader.nextInt();
System.out.println("How much do you wish to deposit?");
Deposit = reader.nextInt();
System.out.println("How much do you with to withdraw?");
Withdrawal = reader.nextInt();
System.out.println("\n" + a1.getName());
}
}
你介意告诉我我做错了什么并解释它吗?
答案 0 :(得分:2)
缺少getBalance()
方法的返回类型,而您返回double类型的变量。声明为: -
public double getBalance(){ // add double as the return-type here
return Balance;
}
另外,如Drew Kennedy所述---通过添加BankAccount类和a1来声明BankAccount类的对象。你还没有在任何地方提到它......
BankAccount a1 = new BankAccount(); // you're missing class name BankAccount
答案 1 :(得分:0)
您的getBalance()
方法需要返回类型。将声明更改为public double getBalance()
。作为旁注,Java约定说不要将变量名的第一个字母大写。遵循约定使您的代码更容易被其他人阅读,这将导致更多更好的响应。
答案 2 :(得分:0)
getBalance()方法没有返回类型,但您要求它返回一个值。另外,请尝试遵循Java命名约定,变量名称不应以大写字母开头。