public class Account
{
static int accountNum;
static int nextAccountNum = 112200;
static double balance;
public static void main(String args[])
{
Account checkingAccount = new Account(1500.00);
Account savingAccount = new Account(1000.00);
Account moneyMarketAccount = new Account(500.00);
checkingAccount.getAccountNumber();
savingAccount.getAccountNumber();
moneyMarketAccount.getAccountNumber();
}
public Account(double bal)
{
balance = bal;
accountNum = nextAccountNum;
nextAccountNum++;
}
}
每次运行它时,我都没有得到任何返回变量。我所看到的只是过程完成的文本。寻求帮助
答案 0 :(得分:1)
你没有输出任何东西。使用System.out.println
输出帐户余额,例如
System.out.println(checkingAccount.getAccountNumber());
另外,请将您的accountNum
和balance
变量设为非static
,否则每个新实例都会覆盖余额和帐号。
答案 1 :(得分:1)
将主函数与将具有多个实例的类分开通常是一种好习惯。 getters和setters方法用于正确封装类变量,因为帐户可能应该具有。下面是一个例子。
<强> Main.java 强>
public class Main {
public static void main(String args[])
{
Account checkingAccount = new Account(1,1500.00);
Account savingAccount = new Account(2,1000.00);
Account moneyMarketAccount = new Account(3,500.00);
System.out.println("Account " + checkingAccount.getAccountNumber()
+ " has balance of: " + checkingAccount.getBalance());
System.out.println("Account " + savingAccount.getAccountNumber()
+ " has balance of: " + savingAccount.getBalance());
System.out.println("Account " + moneyMarketAccount.getAccountNumber()
+ " has balance of: " + moneyMarketAccount.getBalance());
}
}
<强> Account.java 强>
public class Account
{
private int accountNum;
private int nextAccountNum = 112200;
private double balance;
public Account(int accountNum, double balance)
{
this.balance = balance;
this.accountNum = accountNum;
}
public int getAccountNumber() {
return accountNum;
}
public double getBalance() {
return balance;
}
public void setBalance(int balance) {
// check if balance variable is a correct value
// before setting it to the class variable
this.balance = balance;
}
}
答案 2 :(得分:0)
一个问题是accountNum
和balance
被声明为static
。您需要它们作为实例字段,因此Account
的每个实例都有自己的值。
您没有输出的原因是您的main()
方法会创建多个Account
对象但不对它们执行任何操作。
public class Account
{
static int nextAccountNum = 112200;
int accountNum;
double balance;
public static void main(String args[])
{
Account checkingAccount = new Account(1500.00);
Account savingAccount = new Account(1000.00);
Account moneyMarketAccount = new Account(500.00);
checkingAccount.getAccountNumber();
savingAccount.getAccountNumber();
moneyMarketAccount.getAccountNumber();
System.out.println("Checking: " + checkingAccount.toString());
System.out.println("Savings: " + savingAccount.toString());
System.out.println("Money market: " + moneyMarketAccount.toString());
}
public Account(double bal)
{
balance = bal;
accountNum = nextAccountNum;
nextAccountNum++;
}
@Override
public String toString() {
return "Account " + accountNum + ": balance=" + balance;
}
}