如何使用方法在类之间传递信息

时间:2019-03-15 23:45:31

标签: java

我目前正在学习第一门Java课程,并且很难理解方法以及如何在类之间传递信息。

我已经为自己的作业编写了代码,但我一生都不知道如何将taxableIncome和tax从一类传递到另一类。

能否请您查看我的代码并直接指出正确的内容,或者告诉我我做错了什么?我一直在努力让它整周都能正常工作,但是还没有走运。请使您的回答对目前对Java不太了解的人可以理解,在这里输入代码。

我的头等舱代码如下:

/**
 * This program will ask the user for their taxable income, and display that number based on calculations done in the TaxCalculator Class.
 */

import java.util.*;

public class TaxCalculatorTester{
    public static void main(String [] args){

        double taxableIncome = 0; //declare and initialize taxable income
        double tax = 0;
        Scanner input = new Scanner(System.in);

        System.out.println("This program will calculate how much you owe in taxes based on your income."); 
        System.out.println("Please enter your taxable income for this year.");
        taxableIncome = input.nextDouble( );

        TaxCalculator taxObject = new TaxCalculator();
        taxObject.CalculateTax(tax);

        System.out.println("You owe " + tax + " in taxes.");
        System.out.println("Please note this is just a estimate and acutal amount due may differ.");
    }
}

实际计算所有内容的第二类代码如下:

/**
 * This program will calculate how much tax a user owes based on the user input taxable income which is pulled from the TaxCalculatorTester class.
 */

import java.util.*;

class TaxCalculator{

    static double CalculateTax (double taxableIncome){
        double tax = 0.0;


        if (taxableIncome < 9526)
          tax = taxableIncome * .10;
        else if (taxableIncome <= 38700.99)
          tax = taxableIncome * .12;
        else if (taxableIncome <= 82500.99)
          tax = taxableIncome * .22;
        else if (taxableIncome <= 157500.99)
          tax = (taxableIncome * .24);
        else if (taxableIncome <= 200000.99)
          tax = taxableIncome * .32;
        else if (taxableIncome <= 500000.99)
          tax = taxableIncome * .35;
        else
          tax = taxableIncome * .37;
     return tax;
    }
}

1 个答案:

答案 0 :(得分:1)

您必须更改您的:

TaxCalculator taxObject = new TaxCalculator();
taxObject.CalculateTax(tax);

进入:

tax = TaxCalculator.CalculateTax(taxableIncome);

方法CalculateTax(应从小写字母开始)为static,因此您可以调用它而无需创建包含类的对象(在您的情况下为CalculateTax)。

在您的代码中,您将tax作为CalculateTax方法的参数传递,但是tax0。您必须传递用户键入的值,以便taxableIncome

此外,您还必须记住分配方法CalculateTax返回的值,因为在您的代码中您正在传递数据,方法正在进行一些计算,而您并不关心结果(返回值)。 / p>