简体   繁体   English

变量的方法范围(java)

[英]Method Scope of variables (java)

I have a class in java for methods. 我在Java中有一个方法类。 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. 当减法和加法完成时,它们将被分配给各自的变量(当然是自动地),但是当方法完成其工作时,值将被删除,因此当我调用减法/加法的方法时,结果是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. 您在一个对象上调用sum_Difference()方法,并在另一个对象上显示结果。

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. 使用相同的对象来调用所有三个方法。

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

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