Java从单独的方法返回变量

时间:2014-09-17 03:29:22

标签: java

我已经创建了一个工作变更计算器,可以在Driver类" CoinsCalculateTester"从另一个恰当命名的" CoinsCalculate"中调用计算和输出方法。这是两个班级。

CoinsCalculateTester类

import chn.util.*;

public class CoinsCalculateTester
{
    public static void main(String[] args)
    {
        int change;
        ConsoleIO keyboard = new ConsoleIO();
        System.out.print("Please enter amount of change => $0.");
        change = keyboard.readInt();
        CoinsCalculate printOut = new CoinsCalculate(change);
        printOut.calculate();
        printOut.printChange();
    }
}

CoinsCalculate类

public class CoinsCalculate
{

//Instance variables
private int change;
public int q, d, n, p; //Quarters, Dimes, Nickels, and Pennies, Respectively.
public int c; //Declaring var c for change in constructor

//Constructor
public CoinsCalculate (int change)
{
    c = change;
}

public void calculate()
{
    change = change * 100;

    int q = c / 25;
    c = c % 25;

    int d = c / 10;
    c = c % 10;

    int n = c / 5;
    c = c % 5;

    int p = c / 1;
    c = c % 1;



}

public void printChange()
{
    System.out.println("Quarter(s): " +q);
    System.out.println("Nickel(s): " +d);
    System.out.println("Dime(s): " +n);
    System.out.println("Penny(s): " +p);
}
}

当运行Tester时,这是输出:

Please enter amount of change => $0.84
Quarter(s): 0
Nickel(s): 0
Dime(s): 0
Penny(s): 0

我相信我遇到的问题是,一旦完成计算方法,变量就会返回到它们的初始值,所以当在printChange方法中返回它们时,我得到0。我知道我可以将SOP线放在一个方法中并避免所有这些麻烦,但我希望它们采用不同的方法。所以我的问题是,我该怎么做?

2 个答案:

答案 0 :(得分:3)

不要在calculate方法中重新定义这些变量,否则它们会隐藏那些具有相同名称的类级别变量:

q = c / 25;
c = c % 25;

d = c / 10;
c = c % 10;

n = c / 5;
c = c % 5;

p = c / 1;
c = c % 1;

答案 1 :(得分:0)

在方法中声明变量时,其范围仅限于该方法。

您的代码在 calculate()方法中声明了局部变量,一旦方法返回,就会存在 NOT

这些变量与您的公共类变量具有相同的名称,这些变量从未使用过(c除外)。