如何在另一种方法中调用一个方法的整数?

时间:2012-03-04 05:28:27

标签: java string class methods integer

我对使用Java进行编程相当新...但这确实让我感到困惑,我已经搜索了一段时间,我找不到我所寻找的明确答案......但是让我们说我有两种方法

public static void program1 (String[] args) {
    Integer intMoney;
    intMoney = 500;
}

public static void program2 (String[] args) {
    String strYes;
    strYes = JOptionPane.showInputDialog("type yes to subtract 100");
    if((strYes.equals("Yes") || (strYes.equals("yes")))) {
    /*((This is where I call the intMoney from program1) */ - 100;
    }else{
        JOptionPane.showMessageDialog(null, "Thats not yes!");
    }
}

这就是我真的卡住的地方..说我有另外一种方法,比如program1,但是如何在另一种方法中调用program1中的intMoney值呢?

假设我有一个程序,我想在一个单独的方法中声明intMoney,这样当方法程序2重复时,intMoney值不会改变,并且当方法时它将是相同的再次被召唤。

2 个答案:

答案 0 :(得分:2)

首先,你的计划完全出于规则和规则,有很多错误:

  1. intMoney具有功能范围。因此,无法从函数 program1()外部调用它。您必须从此函数返回值才能在另一个函数中使用。
  2. if 中,您正在检查以||分隔的2条件但两个条件都相同。请使用一个。

    public static int program1 () {
    Integer intMoney;
    intMoney = 500;
    return intMoney;
    }
    
    public static void program2 () {
    String strYes;
    strYes = JOptionPane.showInputDialog("type yes to subtract 100");
    if((strYes.equals("Yes") || (strYes.equals("yes")))); {
    program1() - 100
    }else{
    JOptionPane.showMessageDialog(null, "Thats not yes!");
    
    }
    }
    

答案 1 :(得分:0)

你可以'访问program1中的变量,因为它没有作用于方法。你应该这样做:

public class Foo {
    public static Integer intMoney;

    public static void program1(String[] args) {
        intMoney = 500;
    }

    public static void program2(String[] args) {
        String strYes;
        strYes = JOptionPane.showInputDialog("type yes to subtract 100");
        if ((strYes.equals("Yes") || (strYes.equals("yes"))))
        {
            Integer i = intMoney;
            Integer x = i - 100;

        }else{
            JOptionPane.showMessageDialog(null, "Thats not yes!");

        }
    }
}

当然,现在需要先调用program1才能设置变量。您也可以像public static final Integer intMoney = 500;

一样启动它

另外,如果您不使用String [] args参数,那么它们是什么?