Java方法和调用方法太多次了

时间:2017-11-17 19:06:55

标签: java methods parameter-passing

我遇到了Java方法的问题。这段代码应该有三种方法。方法1)输入#员工。方法2)输入每个员工缺席的天数。方法3)计算不存在的平均天数。然后,在Main中,应打印员工数量,缺席天数和缺少的平均天数。很明显,我不明白方法是如何工作的,因为当我运行代码时,用户被问到4倍的员工数量和2倍员工在提供员工数量之前错过的天数,#days absent和average缺席的天数。如何更改代码,以便用户只需输入一次信息?

public static void main(String[] args) {
    /** Asks for the # of employees and their days absent using
     3 methods. 1) Requests number of employees, 2) # of days absent, 3)
     Average # of days absent)*/

    int numEmployeeM, numDaysMissedM;
    double averageNumDaysAbsentM;

    numEmployeeM = numEmployee();
    numDaysMissedM = numDaysMissed(numEmployeeM);
    averageNumDaysAbsentM = averageNumDaysAbsent(numEmployeeM,
            numDaysMissedM);
    System.out.println("\n\tTotal number of employees: " + numEmployeeM +
            "\n\tTotal number of days missed: " + numDaysMissedM +
            "\n\tAverage number of days absent: " + averageNumDaysAbsentM);
}

public static int numEmployee() {
    Scanner keyboard = new Scanner(System.in);

    int numEmployee;

    System.out.print("Number of employees in company:");
    numEmployee = keyboard.nextInt();
    return numEmployee;
}

public static int numDaysMissed(int numEmployee1) {
    Scanner keyboard = new Scanner(System.in);

    int count, numDaysMissed, totalNumDaysMissed;
    count = 1;
    totalNumDaysMissed = 0;
    numEmployee1 = numEmployee();

    while (count <= numEmployee1) {
        System.out.print("Enter number of days missed by Employee #"
                + count + ": ");
        numDaysMissed = keyboard.nextInt();
        totalNumDaysMissed += numDaysMissed;
        count++;
    }
    return totalNumDaysMissed;
}

public static double averageNumDaysAbsent(int numEmployee2,
                                          int totalNumDaysMissed1) {
    double averageDaysMissed;
    numEmployee2 = numEmployee();
    totalNumDaysMissed1 = numDaysMissed(numEmployee2);

    averageDaysMissed = (totalNumDaysMissed1 / numEmployee2);
    return averageDaysMissed;
}

1 个答案:

答案 0 :(得分:1)

简化代码以查看调用的内容:

void main(String[] args)
{
    numEmployeeM = numEmployee();
    numDaysMissedM = numDaysMissed(numEmployeeM);
    averageNumDaysAbsentM = averageNumDaysAbsent(numEmployeeM, numDaysMissedM);
}

int numEmployee()
{
}

int numDaysMissed(int numEmployee1)
{
    numEmployee1 = numEmployee();
}

double averageNumDaysAbsent(int numEmployee2, int totalNumDaysMissed1)
{
    numEmployee2 = numEmployee();
    totalNumDaysMissed1 = numDaysMissed(numEmployee2);
}

因此,当您的代码执行时,它会调用

    • numEmployee
    • numDaysMissed
      • numEmployee
    • averageNumDaysAbsent
      • numEmployee
      • numDaysMissed
        • numEmployee

这会给出预期的总计数1x averageNumDaysAbsent,2x numDaysMissed和4x numEmployee

numDaysMissedaverageNumDaysAbsent中,你覆盖了你的输入参数并使它们变得无用

尝试删除这些行,它应该按预期工作