嗨,我有麻烦让我的程序正常运行。我能够清除任何语法错误,但现在我已经发布了我的输出。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