嗨,我有麻煩讓我的程序正常運行。我能夠清除任何語法錯誤,但現在我已經發布了我的輸出。while循環嵌套的if/else語句
首先,在第一個IF語句中,它會提示要求人員同時輸入他們的姓名和部門,以便在輸出時,名稱是空白的,只有部門有輸入。我認爲這是整個IF語句的事情,因爲如果我將「String name」更改爲input.next,則名稱提示正確,但將dept和totalHrsWkd合併在一起。
此外,當測試我的程序時,它輸入totalHrsWkd的負數時崩潰。它會在一行中顯示兩條打印語句,然後崩潰JCreator。
我很感激任何關於此事的幫助,謝謝!
public static void main(String[] args)
{
// TODO code application logic here
int attempt = 1, employeeID = 0;
double hoursWorked = 0.0;
double overtimeHrs = 0.0;
double totalHrsWkd = 0.0;
Scanner input = new Scanner(System.in);
while(attempt < 4)
{
System.out.println("Enter your employee ID: ");
employeeID = input.nextInt();
if(employeeID == 12345678)
{
System.out.printf("Enter your name: ");
String name = input.nextLine();
System.out.printf("Enter your department: ");
String dept = input.nextLine();
System.out.printf("Enter your hours worked including overtime: ");
totalHrsWkd = input.nextDouble();
while(totalHrsWkd < 0)
{
System.out.printf("Try again! Hours worked cannot be negative.");
System.out.printf("Enter your hours worked including overtime: ");
}
overtimeHrs = totalHrsWkd - 40;
hoursWorked = totalHrsWkd - overtimeHrs;
if(overtimeHrs <= 0)
{
}
else if(overtimeHrs == 0)
{
}
else if(hoursWorked == totalHrsWkd)
{
}
else if(hoursWorked == 40)
{
}
System.out.printf("Name: %s\n" + "Dept: %s\n" +
"Hours Worked: %.2f\n" + "Overtime Hours: %.2f\n"
+ "Total Hours Worked: %.2f\n", name, dept,
hoursWorked, overtimeHrs, totalHrsWkd);
attempt = 3;
}
else
{
if(attempt < 3)
{
System.out.println("Invalid ID! Try again." );
}
else
{
System.out.println("Invalid ID! 0 attempts left. Exiting program!");
}
}
++attempt;
}
System.exit(0);
}
}
'totalHrsWkd = input.nextDouble();'應該放在while循環中。否則,你只是在一個無限循環中運行,沒有任何變化'totalHrsWkd' – biziclop 2012-02-21 20:49:18
你爲什麼選擇使用'Scanner'?這幾乎不適用於交互式程序(並導致像你在這裏看到的問題)。相反,使用['BufferedReader.readLine'](http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedReader.html)。 – 2012-02-21 20:50:23
是的,這是我的Java 1類的編程任務。本質上,老師給我們提供了僞代碼,我們需要編寫程序。到目前爲止,我們只處理Scanner類。我甚至沒有在我們的書中遇到過BufferedReader.readLine。 – Abweichung 2012-02-21 20:54:21