我在这个小程序中有两个班。该计划的第一部分工作正常。
public class PayCheck
{
private double hourlyRate, hoursWorked, grossPay, netPay;
final double federalTaxAmount = 0.15;
final double stateTaxAmount = 0.09;
final double FICAAmount = 0.07;
private String lastName, firstName;
public PayCheck()
{
hourlyRate = hoursWorked = grossPay = netPay = 0;
lastName = firstName = "unknown";
}
public PayCheck(double inRate, double inHours, String inLast, String inFirst)
{
hourlyRate = inRate;
hoursWorked = inHours;
lastName = inLast;
firstName = inFirst;
}
public String setLastName()
{
return lastName;
}
public String setFirstName()
{
return firstName;
}
public double setHourlyRate()
{
if (hourlyRate > 5)
{
if (hourlyRate < 100)
{
hourlyRate = hourlyRate;
}
}
else
{
hourlyRate = 0;
}
return hourlyRate;
}
public double setHoursWorked()
{
if (hoursWorked < 0)
if (hoursWorked > 100)
{
hoursWorked = hoursWorked;
}
else
{
hoursWorked = 0;
}
return hoursWorked;
}
public double getGross()
{
grossPay = hoursWorked * hourlyRate;
return grossPay;
}
public double getNet()
{
netPay = grossPay - (grossPay * federalTaxAmount) - (grossPay * stateTaxAmount) - (grossPay * FICAAmount);
return netPay;
}
public String toString()
{
return "Last Name: " + lastName + "\nFirst Name: " + firstName + "\nGross Pay: "
+ this.getGross() + "\nNet Pay: " + this.getNet() + "\nFederal Tax Amount: "
+ (grossPay * federalTaxAmount) + "\nState Tax Amount: " + (grossPay * stateTaxAmount)
+ "\nFICA Amount: " + (grossPay * FICAAmount);
}
}
然后引用上面代码的另一部分必须处于循环中,即使输入是终止循环的正确输入,该循环也永远不会结束。
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
String lastName, firstName, choice;
double hours, rate;
boolean again = true;
PayCheck emp1;
while(true)
{
System.out.print("Please enter the Last Name: ");
lastName = key.next();
System.out.print("Please enter the First Name: ");
firstName = key.next();
System.out.print("Please enter the number of hours: ");
hours = key.nextDouble();
System.out.print("Please enter the pay rate per hour: ");
rate = key.nextDouble();
emp1 = new PayCheck(rate, hours, lastName, firstName);
System.out.println(emp1.toString());
System.out.print("Do you want to another entry (Y/N)? ");
choice = key.next();
if (choice.toLowerCase() == "n")
{
break;
}
}
}
}
是否有更好的方法来终止循环,因为这个循环根本没有终止。
答案 0 :(得分:2)
不要将Java中的字符串与==
进行比较。您必须使用String.equals
,例如choice.toLowerCase().equals("n")
。
答案 1 :(得分:1)
choice.toLowerCase() == "n"
比较字符串引用,而不是内容。
使用"n".equals(choice.toLowerCase())
或类似内容来比较内容。
您可以用
替换表面上无限的循环do {
} while (!"n".equals(choice.toLowerCase()))
当然,这泄漏了<{1}}在循环之外的范围,但无论如何你都是这样做的。