【发布时间】:2011-03-08 13:00:45
【问题描述】:
我正在尝试 Java 编程书中的几个练习。我有以下代码:
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”作为员工姓名时,程序就会继续运行。我尝试用任何其他字符串替换“停止”,但它仍然不起作用。但是当我尝试用“stop”初始化employeeName 时,程序会立即退出,这是意料之中的。我在这里做错了什么?
此外,在第一个循环之后,程序总是跳过询问员工姓名。我尝试用employeeName = input.next(); 替换employeeName = input.nextLine();,它不再跳过它。不过我想知道,有什么办法可以让它在使用employeeName = input.nextLine();时不跳过输入?
提前感谢您的帮助!
【问题讨论】:
标签: java loops while-loop