Tôi xin lỗi trước nếu mã này không được định dạng chính xác, cố gắng dán thay vì nhập lại từng dòng. Nếu nó không đúng, ai đó có thể cho tôi biết một cách dễ dàng để dán nhiều dòng mã cùng một lúc?không thể tham chiếu tĩnh đến trường không tĩnh
câu hỏi chính của tôi là tôi tiếp tục nhận được một thông báo lỗi: Cannot make a static reference to the non-static field balance.
Tôi đã cố gắng làm cho phương pháp tĩnh, không có kết quả, và làm cho phương pháp chính không tĩnh bằng cách loại bỏ "tĩnh" từ tiêu đề , nhưng sau đó tôi nhận được thông báo: java.lang.NoSuchMethodError: main Exception in thread "main"
Có ai có ý tưởng nào không? Bất kỳ trợ giúp được đánh giá cao.
public class Account {
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
System.out.println("Balance is " + account.getBalance());
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
System.out.println("The account was created " + account.getDateCreated());
}
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public java.util.Date dateCreated;
public Account() {
}
public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public void setId(int i) {
id = i;
}
public int getID() {
return id;
}
public void setBalance(double b){
balance = b;
}
public double getBalance() {
return balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double interest) {
annualInterestRate = interest;
}
public java.util.Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(java.util.Date dateCreated) {
this.dateCreated = dateCreated;
}
public static double withdraw(double balance, double withdrawAmount) {
double newBalance = balance - withdrawAmount;
return newBalance;
}
public static double deposit(double balance, double depositAmount) {
double newBalance = balance + depositAmount;
return newBalance;
}
}
Tôi "không chắc chắn lý do tại sao bạn thậm chí có số dư làm đối số cho phương thức account.withdraw() và account.deposit(). Vì tài khoản _knows_ số dư, câu trả lời đơn giản nhất là xóa chúng khỏi phương thức Ngoài ra, nếu bạn thực sự muốn chúng, bạn cần phải nói account.balance trong các cuộc gọi từ main() – user949300
để định dạng tab thay đổi thành dấu cách và chọn mã sau khi bạn đã dán và nhấn ctrl-k để tự động thụt lề –