繁体   English   中英

初始化实例变量以在方法外部使用

[英]Initializing instance variable for use outside of the method

我的一种方法中有一个名为“数量”的变量,但我需要在另一种方法中引用它。 我不确定使用的语法。

这是代码:

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

如何在方法之外使用变量“amount”和“bankID”?

两种方式:

  1. 通过参数将amount传递给其他方法

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

  2. 创建一个实例变量,以便您可以在 class scope 内访问它

    private int amount;

    如果你go用这个路由,最好用getter和setter。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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