我希望用户输入付费率和工作小时数。如果小时数为40或以下,则将工资率和小时数相乘。所有这一切都发生在一个方法中,主要方法应该调用它。但是,我的程序对值没有任何作用。
package homework6;
import java.util.Scanner;
public class Homework6 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your pay rate.");
double r = console.nextDouble();
System.out.println("How many hours did you work this week?");
int h = console.nextInt();
double T1 = getTotalPay(r, h);
}
public static double getTotalPay(double r, int h){
/*If the number of hours is less than or equal to 40, it simply
multiplies them together and returns the result.*/
if (h <= 40) {
return r*h;
}
}
}
答案 0 :(得分:1)
最有可能的是,您只需要打印返回的值:
...
double T1 = getTotalPay(r, h);
System.out.println("Total pay: " + T1);
作为一种风格问题,Java变量应该以较低的字母开头。您应该将名称T1
更改为t1
(或者更好地更改为totalPay
更易于理解的内容。)
只是为了澄清:以上内容属于main()
方法。
如果您想要花哨,可以将结果格式化为货币:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your pay rate.");
double r = console.nextDouble();
System.out.println("How many hours did you work this week?");
int h = console.nextInt();
double totalPay = getTotalPay(r, h);
System.out.println("Total pay: " +
NumberFormat.getCurrencyInstance().format(totalPay)
);
}
答案 1 :(得分:0)
首先,您需要打印此返回值:
System.out.println(T1);
其次,如果声明的返回类型不是 void,那么 getTotalPay(double r,int h)方法必须始终返回一些内容或抛出异常即可。现在它只在条件满足时返回一些东西。你有没有得到这个编译?此方法应如下所示:
public static double getTotalPay(double r, int h){
if (h <= 40){
return r*h;
} else {
return 0;
}
}