我在java中有一个用于方法的类。基本上这个类接收一个整数数组,添加数字并减去它们,返回和和减法。我在顶部声明了变量(不是在特定方法中)。减法和加法完成后,它们被分配给各自的变量(当然是自动的),但是当方法完成其工作时,值被删除,所以当我调用减法/加法的方法时结果是一个 0。
据我所知,这些值不应该为空,因为它们不是在方法内部而是在所有方法之外初始化的,所以范围不应该结束。请问有什么帮助吗?
//方法类
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);
}
}
我所在的班级
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();
}
}