有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java问题将参数传递给不同公共类中的构造函数

我很难将hourshourlyWage参数传递给Paycheck类中的构造函数。问题如下:

symbol: variable hours
location : class Paycheck

它在公共类工资支票中的每小时或每小时工资实例中重复

代码如下

import java.util.Scanner;

public class PayDayCalculator {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Hourly wage: ");
        double hourlyWage = in.nextDouble();
        System.out.println("Hours worked: ");
        double hours = in.nextDouble();

        Paycheck paycheck = new Paycheck(hourlyWage, hours);
        System.out.println("Pay: " + paycheck.getPay());
    }
}

public class Paycheck {
    private double pay = 0;
    private double overtime = 0;
    private double overtimePay = 0;

    /*double hours;
    double hourlyWage; */
    Paycheck(double hourlyWage, double hours) {
        setPay(0);
    }

    public void setPay(double newPay) {
        if (hours > 40) {
            overtime = hours % 40;
            hours = hours - overtime;
        }
        overtimePay = hourlyWage * 1.5;
        pay = (hours * pay) + (overtime * overtimePay);
    }

    public double getPay() {
        return pay;
    }
}

共 (3) 个答案

  1. # 1 楼答案

    您的setPay方法引用的是hourshourlyWage,这是传递给构造函数的参数,使它们仅对构造函数是局部的。它们不适用于类中的所有方法。如果希望所有方法都能访问它们,则需要在类级别取消注释

    double hours;
    double hourlyWage;
    
    Paycheck(double hourlyWage, double hours) {
        this.hourlyWage = hourlyWage;
        this.hours = hours;
        setPay(0);
    }
    
  2. # 2 楼答案

    您已经注释掉了成员变量hours

    /*double hours;
    double hourlyWage; */
    

    但仍然尝试引用它,例如:

    if (hours > 40) {
        overtime = hours%40;
        hours = hours - overtime;
    }
    

    如果需要此变量,请取消注释

  3. # 3 楼答案

    hourshourlyWage未定义

    取消对本部分的注释-

    /*double hours;
    double hourlyWage; */