Erik
Erik

Reputation: 1

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?

Upvotes: 0

Views: 134

Answers (1)

Mingyu
Mingyu

Reputation: 33369

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;
    }
    

Upvotes: 1

Related Questions