我正在尝试Java编程书籍中的几个练习。我的代码如下:Java中的“while”问题
import java.io.*;
import java.util.Scanner;
public class Ex420
{
public static void main(String args[])
{
String employeeName = "";
double workHours,excessHours, hourlyRates, grossPay;
Scanner input = new Scanner(System.in);
while (employeeName != "stop")
{
System.out.printf("\nInput employee name or stop to exit: ");
employeeName = input.nextLine();
System.out.printf("Input working hours: ");
workHours = input.nextDouble();
System.out.printf("Input hourly rates: ");
hourlyRates = input.nextDouble();
if (workHours <= 40 & workHours >= 0)
{
excessHours = 0;
grossPay = hourlyRates * workHours;
System.out.printf("%s's gross pay is $%.2f\n", employeeName, grossPay);
}
else if (workHours > 40)
{
excessHours = workHours - 40;
grossPay = hourlyRates * 40 + 1.5 * hourlyRates * excessHours;
System.out.printf("\n%s's worked for %.1f excess hours.\n", employeeName, excessHours);
System.out.printf("%s's gross pay is $%.2f\n", employeeName, grossPay);
}
else
{
System.out.printf("Invalid input. Please try again.");
}
} // end while
} // end main
} // end class Ex420
问题是,while循环似乎没有工作。每当我输入“stop”作为employeeName时,程序就会继续。我尝试用任何其他字符串替换“停止”,它仍然不起作用。但是当我尝试使用“stop”初始化employeeName时,程序立即退出,这是预期的。我在这里做错了什么?
此外,在第一个循环之后,程序总是跳过询问employeeName。我试着用employeeName = input.next();
替换employeeName = input.nextLine();
,它不再跳过它。我想知道,有没有什么办法可以使它在使用employeeName = input.nextLine();
时不会跳过输入?
在此先感谢您的帮助!
您可能是指'while(!“stop”.equals(employeeName))'以匹配示例代码的含义,对吧? – maerics 2010-06-26 02:54:06
我喜欢'尤达'的表情:) – VoodooChild 2010-06-26 02:55:05