简体   繁体   中英

Initializing instance variable for use outside of the method

I have a variable called "amount" in one of my methods but I need to make reference to it in another method. I'm not sure of the syntax used.

Here is the code:

public static void startup()
{
    String message = "Welcome to Toronto Mutual!";
    //prompts user to enter their employee ID
    String logIn = JOptionPane.showInputDialog("Please enter your employee `enter code here`ID.");
    int employeeID = Integer.parseInt(logIn);

    String input = JOptionPane.showInputDialog("Please enter the transaction `enter code here`type, bank ID and amount all separated by a comma.");
    input=input.toUpperCase();
    if (input.equals("END")){
        JOptionPane.showMessageDialog(null,"Goodbye.");
        System.exit(0);
    }
    else
    {
        int balance = 100;
        String []transaction = new String[3];
        transaction = input.split(",");
        String type = transaction[0]; 
        int bankID = Integer.parseInt(transaction[1]);
        type=type.toUpperCase();
... // there's more but it's irrelevant

How do I use the variable "amount" and "bankID" outside of the method?

Two ways:

  1. Pass amount to the other method through argument

    private void otherMethod(int amount) {...}

  2. Create an instance variable so that you can access it within the class scope

    private int amount;

    If you go with this route, it is better to use getter and setter.

     public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM