Dee*_*end 0 java if-statement while-loop
我只是在学习Java,在Deitel和Deitel的书"Java如何编程"中阅读教程,所以请原谅我正在犯的任何基本错误.我理解我的方法可能不是最好的,但我希望能够改进这一点.
我的问题是我相信我错误地构建了我的程序.执行程序时,正在输出IF和ELSE选项.
如果有人能告诉我为什么两个选项都在执行,那将非常感激
困境
package controlStatments;
import java.util.Scanner;
public class Review_4_20
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Declare Variables
double employeeOneRate;
double employeeOneHours;
double employeeTwoRate;
double employeeTwoHours;
double employeeThreeRate;
double employeeThreeHours;
int calculator;
double employeeOneTotalPay;
double employeeOneNormalPay;
double employeeOneTotalPayOverTime;
double overTimeRate;
//Initiate Variables
employeeOneRate = 0;
employeeOneHours = 0;
employeeTwoRate = 0;
employeeTwoHours = 0;
employeeThreeRate = 0;
employeeThreeHours = 0;
calculator = 0;
employeeOneTotalPay = 0;
employeeOneTotalPayOverTime = 0;
overTimeRate = 1.5;
employeeOneNormalPay = 0;
//Create While Loop
while (calculator != -1)
{
//Prompt user to input details
System.out.print("\n\nPlease input the first employees rate");
employeeOneRate =input.nextDouble();
System.out.print("Please input the first employees Hours");
employeeOneHours =input.nextDouble();
if (employeeOneHours <= 40)
{
employeeOneTotalPay = employeeOneHours * employeeOneRate;
System.out.printf("\nNormal time pay is: %.2f", employeeOneTotalPay);
}
else
employeeOneNormalPay = employeeOneRate * 40;
employeeOneTotalPayOverTime = (employeeOneHours - 40) * (employeeOneRate * overTimeRate) + employeeOneNormalPay;
System.out.printf("\n\nTotal Pay including Overtime is: %.2f", employeeOneTotalPayOverTime);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您忘记了else语句中的括号.
我觉得它应该是这样的:
if (employeeOneHours <= 40)
{
employeeOneTotalPay = employeeOneHours * employeeOneRate;
System.out.printf("\nNormal time pay is: %.2f", employeeOneTotalPay);
}
else {
employeeOneNormalPay = employeeOneRate * 40;
employeeOneTotalPayOverTime = (employeeOneHours - 40) *
(employeeOneRate * overTimeRate) + employeeOneNormalPay;
System.out.printf("\n\nTotal Pay including Overtime is: %.2f", employeeOneTotalPayOverTime);
}
Run Code Online (Sandbox Code Playgroud)
如果不设置括号,则第一行包含在IF/ELSE语句中.