Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在两个方法之间交换来自不同类的变量_Java - Fatal编程技术网

Java 在两个方法之间交换来自不同类的变量

Java 在两个方法之间交换来自不同类的变量,java,Java,我在自学Java,我还是个新手,但我想澄清一下在不同方法之间调用变量的问题。我在一个类中有两个不同于主类的方法,它们在taxes中使用相同的变量 第一种方法: public String getFinalPrice(double taxes, int quantity, double beforeTax){ double taxValue = taxes; double afterPrice = (beforeTax * quantity) * (1+taxes/100); r

我在自学Java,我还是个新手,但我想澄清一下在不同方法之间调用变量的问题。我在一个类中有两个不同于主类的方法,它们在
taxes
中使用相同的变量

第一种方法:

public String getFinalPrice(double taxes, int quantity, double beforeTax){

  double taxValue = taxes;

  double afterPrice = (beforeTax * quantity) * (1+taxes/100);

  return currency.format(afterPrice);

}
第二种方法:

public String getTaxAmount(double taxes, double total){

    total *= (taxes/100);
    return currency.format(total);
}
您可以看到,这两种方法使用的
taxes
变量在程序方面是相同的。现在我的问题是如何从第一个方法中获取
taxValue
变量,并在第二个方法中使用它。如何从用户处获取税款并将其放入
getFinalPrice
方法,然后使用
taxValue
变量获取用户输入的税款并在
getTaxAmount
方法中获取。我想基本上去掉
getTaxAmount
方法的税输入:

我想将
getTaxAmount
方法更改为:

public String getTaxAmount(double total){

  total*=(taxValue/100);

  return currency.format(total);

}

您可以创建一个名为
taxes
的实例字段,以及第三种方法来更改该字段的值。在Java中,更改字段值的方法通常使用“getter/setter”模式实现,在这种情况下,更改值的方法称为
set
,在您的示例中:
settax

public class MyClass {
    private double taxes;

    public void setTaxes(double taxes) {
        this.taxes = taxes;
    }

    public String getTaxAmount(double total){

        total*=(taxes/100);

        return currency.format(total);
    }

    public String getFinalPrice(int quantity, double beforeTax){

        double afterPrice = (beforeTax * quantity) * (1+taxes/100);

        return currency.format(afterPrice);
    }
}

首先我想澄清你对变量多重声明的怀疑,有两种类型的作用域,第一种是全局的,第二种是局部的。正如您所看到的,您在第一种方法中定义了TAXS变量,该变量的局部作用域仅在get final price下,在该方法之外,该变量不存在,当您在第二种方法中定义TAXS时,该变量只存在于该方法中。当您在任何方法或块之外定义变量时,它就得到了全局范围,因此它在程序中无处不在


要在其他方法中使用taxValue,可以将taxValue设置为全局变量(在方法外部定义),然后也可以在其他方法中使用它