Tôi đang thử một số bài tập từ một cuốn sách lập trình Java. Tôi có mã bên dưới:Vấn đề với "while" trong 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
Vấn đề là, vòng lặp while dường như không hoạt động. Bất cứ khi nào tôi nhập "stop" là employeeName, chương trình chỉ tiếp tục. Tôi đã thử thay thế "stop" bằng bất kỳ String nào khác và nó vẫn không hoạt động. Nhưng khi tôi thử khởi tạo employeeName với "stop", chương trình sẽ thoát ngay lập tức. Tôi làm gì sai ở đây?
Hơn nữa, sau vòng lặp đầu tiên, chương trình luôn bỏ qua yêu cầu employeeName. Tôi đã thử thay thế employeeName = input.nextLine();
bằng employeeName = input.next();
và nó không bỏ qua nữa. Tôi tự hỏi, có cách nào tôi có thể làm cho nó không bỏ qua đầu vào khi sử dụng employeeName = input.nextLine();
?
Cảm ơn bạn đã trợ giúp!
Bạn có thể có nghĩa là 'while (!" Stop ".equals (employeeName))' để khớp với ý nghĩa của mã ví dụ, phải không? – maerics
Tôi thích biểu thức 'Yoda' :) – VoodooChild