使用方法更改Java中对象的静态变量的值

时间:2020-07-18 16:22:16

标签: java methods static setter

我正在尝试使用方法在Java中创建ATM。我正在尝试调用更改对象(平衡)的变量(总计)的方法。我已经成功创建了对象并设置了它的起始值,但是我不知道如何创建一个可以改变该方法的方法。我不确定设置方法和获取方法将如何应用,因为一切都是静态的。有什么建议吗?

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以这样做:

import java.util.Scanner;
class Main {

private static Scanner in;
private static Balance balance;

public static void main (String[] args) {
  in = new Scanner(System.in);
  balance = new Balance();

  while(true) {
    System.out.println("Main menu:");
    System.out.println("1. Check Balance");
    System.out.println("2. Withdraw");
    System.out.println("3. Deposite");
    System.out.println("4. Exit");

    int n = in.nextInt();

    switch (n) {
      case 1 : displayBalance();
               break;
      case 2 : withdraw();
               break;
      case 3 : deposite();
               break;
      default : return;
    }
  }
}

private static void displayBalance() {
  System.out.println(balance.getBalance());
}

private static void withdraw() {
  double currentBalance = balance.getBalance();

  System.out.println("Enter amount to be withdrawn : ");
  double withdrawAmount = in.nextDouble();
  double balanceAfterWithdraw = currentBalance - withdrawAmount;

  if (balanceAfterWithdraw > 0) {
    balance.setBalance(balanceAfterWithdraw);
    System.out.println(withdrawAmount + " withdrawn.");
    System.out.println("Your new balance is : " + balance.getBalance());
  } else
    System.out.println("You don't have sufficient balance !!!");
}

private static void deposite() {
  double currentBalance = balance.getBalance();

  System.out.println("Enter amount to deposit : ");
  double depositeAmount = in.nextDouble();
  double balanceAfterDeposit = currentBalance + depositeAmount;

  balance.setBalance(balanceAfterDeposit);
  System.out.println(depositeAmount + " deposited.");
  System.out.println("Your new balance is : " + balance.getBalance());
  }
}


public class Balance {

  private double balance;

  public Balance() {
    this.balance = 100;
  }

  public double getBalance() {
    return balance;
  }

  public void setBalance(double amount) {
    this.balance = amount;
  }

}

答案 1 :(得分:1)

您的setter和getter可能类似于以下代码片段。我将total设置为private,因为它只能由setter和getter函数访问。然后,您可以通过startVal.setTotal(100);

来设置值
class balance {

    private int total;

    int getTotal() {
        return total;
    }

    void setTotal(int total) {
        this.total = total;
    } 

}