我正在尝试为我的 java 类编写一些简单的代码,我遇到了两个问题。对不起,如果这对你们大多数人来说似乎很容易,我只是从 Java 开始。我遇到的第一个问题是循环不能正常继续。它运行一次就好了,如果在开始时输入“quit”就会退出,但运行一次后,它不会让用户输入另一个值作为emp name。它直接从最后一行输入emp名称到循环的第一行,输入小时费率,没有机会输入新名称或退出。
我的第二个问题是我的 if 语句试图确保输入的小时费率和工作时间值大于 0。如果输入 0,它会给出错误消息,但如果输入负数,程序会继续没有什么是错的。我如何确保输入的值只是一个正双精度,并且它不会接受负双精度或零?
// Program to Calculate Payroll
import java.util.Scanner;
import java.text.DecimalFormat;
class Payroll
{
public static void main(String args[])
{
Scanner myScanner = new Scanner(System.in);
String empName;
double hourlyRate;
double hoursWorked;
double grossPay;
double netPay;
double taxes;
DecimalFormat money = new DecimalFormat("$.00");
//Get User Information
System.out.print( "Enter employee name or enter 'quit' when finished. " );
empName = myScanner.nextLine();
while (!empName.equals("quit"))
{
System.out.print( "What is their hourly rate? $");
hourlyRate = myScanner.nextDouble();
if (hourlyRate <= 0)
{
System.out.println( "Value is not valid, please enter an amount above zero.");
System.out.print( "What is their hourly rate? $");
hourlyRate = myScanner.nextDouble();
}
System.out.print( "How many hours did they work? ");
hoursWorked = myScanner.nextDouble();
if (hoursWorked <= 0)
{
System.out.println( "Value is not valid, please enter an amount above zero.");
System.out.print( "How many hours did they work? ");
hoursWorked = myScanner.nextDouble();
}
//Calculate Pay and Taxes
grossPay = hourlyRate * hoursWorked;
taxes = .13 * grossPay;
netPay = grossPay - taxes;
//Display All Information
System.out.print( "Employee name: ");
System.out.println(empName);
System.out.print( "Hourly Rate: ");
System.out.println(money.format(hourlyRate));
System.out.print( "Hours Worked: ");
System.out.println(hoursWorked);
System.out.print( "Gross Pay = ");
System.out.println(money.format(grossPay));
System.out.print( "Federal Taxes = ");
System.out.println(money.format(taxes));
System.out.print( "Net Pay = ");
System.out.println(money.format(netPay));
System.out.print( "Enter employee name or enter 'quit' when finished. " );
empName = myScanner.nextLine();
}
System.out.println( "Thank you for using this payroll program.");
}
}