gpt4 book ai didi

java - 如何修复返回值未显示在我的方法之一上的问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:18:56 24 4
gpt4 key购买 nike

我尝试从 4 个方法中的两个返回值,以便我可以在 final方法上使用打印输出。返回值没有显示,我的结果是 null 和 0.0。

import java.util.*;
public class payroll {
static Scanner console = new Scanner(System.in);
static double hour;
static String employee;
static double rate;
static double gross_pay;
static double tax;
static double deduction;
static double net_pay;
public static void main(String[] args) {
name();
number(hour, rate, tax, gross_pay, deduction, net_pay);
print();
}
public static String name() {
System.out.print("Please enter employee's name: ");
String employee = console.nextLine();

return employee;

}
public static double[] number(double hour, double rate, double tax, double gross_pay, double deduction, double net_pay) {

double[] pay = new double[7];
pay[1] = hour;
pay[2] = rate;
pay[3] = tax;
pay[4] = gross_pay;
pay[5] = deduction;
pay[6] = net_pay;

System.out.print("Please enter number of hours worked: ");
pay[1] = console.nextDouble();

System.out.print("Please enter rate of pay: ");
pay[2] = console.nextDouble();


System.out.print("Please enter federal tax rate: ");
pay[3] = console.nextDouble();

pay[4]= hour*rate;
pay[5] = gross_pay*tax;
pay[6] = gross_pay-deduction;


return pay;

}
public static void print() {
System.out.printf("Employee's Name: " + employee + "\n" +
"Hours Worked: " + hour + "\n" +
"Hourly Pay: " + rate + "\n" +
"Gross Pay: " + gross_pay + "\n" +
"Tax Deducted: " + deduction + "\n" +
"Net Pay: " + net_pay);

}

}

预期结果是员工的姓名和方法中进行的计算。

最佳答案

这里的问题是您没有将返回值分配给任何东西。

通常你会做类似的事情

employee = name();

但要提到的其他一点是,您将 employee 等声明为字段,因此可以通过方法直接访问它们

例如

public static void name() {  // do not return any thing
System.out.print("Please enter employee's name: ");

// do not de-declare, just use the field
employee = console.nextLine();

}

这使用起来是正确的,因为您没有将任何参数传递给 print 并且打印出字段的值

关于java - 如何修复返回值未显示在我的方法之一上的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com