请参考以下代码
public class Account {
private String firstName;
private String lastName;
private int accountNumber;
private int apin;
private double abalance;
public Account(String fname, String lname, int anumber, int pin,
double balance) {
fname = firstName;
lname = lastName;
anumber = accountNumber;
pin = apin;
balance = abalance;
System.out.println("variables set");
}
public String getfirstName() {
return firstName;
}
public String getlastName() {
return lastName;
}
public int getaccountNumber() {
return accountNumber;
}
public int getpin() {
return apin;
}
public double getbalance() {
return abalance;
}
}
public class bank {
private Account[] account;
boolean flag = false;
Account returnAccount;
public Account bank(int anum, int pin) {
account = new Account[3];
account[0] = new Account("Steve", "Kom", 1234, 333, 50000);
account[1] = new Account("Mack", "Dumbo", 2345, 123, 80000);
account[2] = new Account("Xina", "Patt", 2145, 222, 40000);
System.out.println(account[0].getaccountNumber());
for (Account aa : account) {
System.out.println(aa.getaccountNumber());
}
return returnAccount;
}
}
在上面的代码中,get方法总是返回0,为什么变量没有设置。 我很困惑我做错了什么。
答案 0 :(得分:1)
构造函数中的赋值语法错误:
public Account(String fname, String lname, int anumber, int pin,
double balance) {
fname = firstName; //incorrect assignment
lname = lastName; //incorrect assignment
anumber = accountNumber; //incorrect assignment
pin = apin; //incorrect assignment
balance = abalance; //incorrect assignment
System.out.println("variables set");
}
应该是
public Account(String fname, String lname, int anumber, int pin, double balance) {
firstName = fname; //switched - correct assignment
lastName = lname ; //switched - correct assignment
accountNumber = anumber; //switched - correct assignment
apin = pin ; //switched - correct assignment
abalance = balance; //switched - correct assignment
System.out.println("variables set");
}
答案 1 :(得分:0)
您在构造函数
中设置了错误的值fname = firstName;
将其更改为
this.firstName = fname;
答案 2 :(得分:0)
public Account(String fname, String lname, int anumber, int pin,
double balance) {
fname = firstName; // swap
lname = lastName; // swap
anumber = accountNumber;
pin = apin;
balance = abalance;
System.out.println("variables set");
}