简体   繁体   中英

Method Scope of variables (java)

I have a class in java for methods. Basically this class receives an array of integer numbers, adds the numbers & subtracts them too, returns the sum and the subtraction. I declared the variables at the top (not in a particular method). When the subtraction and the addition are done they're assigned to their respective variables (automatically, of course), BUT when the method is finished doing its job the values are deleted, so when I call a method of the subtraction/addition the result is a 0.

As far as I know the values shouldn't be empty because they're not initialized inside a method but outside all methods, so the scope shouldn't have ended. Any help, please ?

//Class of the methods

    package chap3;

    import javax.swing.JOptionPane;

    /**
    *
    * @author jtech
    */
    public class SimpleArithmeticMethods
    {
   int sum;
   int subtraction;

public void sum_Difference(int[] nums)
{        
    int[] inpNums = nums; 

    sum = inpNums[0] + inpNums[1];
    subtraction = inpNums[1] - inpNums[0]; 

}

public void getSum()
{
     JOptionPane.showMessageDialog(null,"The sum is: "+sum, "Result.", JOptionPane.INFORMATION_MESSAGE);
}

public void getDifference()
{
    JOptionPane.showMessageDialog(null,"The difference is: "+subtraction, "Result.", JOptionPane.INFORMATION_MESSAGE);
}

}    

The class from which I run

 package chap3;

 import javax.swing.JOptionPane;

 /**
  *
 * @author jtech
 */
public class SimpleArithmetic 
{

  public static void main(String[] args)
  {
    String[] strInptNums = new String[2];
    int[] inptNums = new int[2];         

    SimpleArithmeticMethods obtainSum = new SimpleArithmeticMethods();
    SimpleArithmeticMethods obtainDifference = new SimpleArithmeticMethods();
    SimpleArithmeticMethods workSum_Difference = new SimpleArithmeticMethods();

    for (int counter = 0; counter <= 1; counter++)
    {
        strInptNums[counter] = JOptionPane.showInputDialog(null, "Input a number, smallest first", "Input Data.", JOptionPane.QUESTION_MESSAGE);
        inptNums[counter] = Integer.parseInt(strInptNums[counter]);
    }        

    workSum_Difference.sum_Difference(inptNums);
    obtainSum.getDifference(); 
    obtainDifference.getDifference();
  }
}

You're calling the sum_Difference() method on one object, and display the results using another object.

That's like storing a message in a bottle, and then looking if the message is in another bottle. Use the same object to call all three methods.

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