您好,我无法让我的程序正常运行。我能够清除任何语法错误,但现在我已经发出了我的输出。
首先,在第一个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);
}
}
答案 0 :(得分:3)
问题在于
employeeID = input.nextInt();
仅从输入流中读取下一个数字序列。但是,为了实际键入员工ID,您还必须按Enter键。 Enter键仍然在等待输入,所以下次调用时
String name = input.nextLine();
Scanner
课程“哦,这是一个Enter键,我想用户想要一个空名。”你甚至没有机会输入一个名字,这就是为什么你的程序似乎同时提出两个问题(名称和部门)。
如果您希望继续使用Scanner
课程,我建议您避免使用nextInt()
等方法,并始终使用nextLine()
。当然,您必须使用类似的东西将用户键入的数字转换为Java整数
parseInt()
答案 1 :(得分:2)
attempt = 3; // Seems suspicious
attempt++; // I think it's more appropriate in loops of this kind than ++attempt
答案 2 :(得分:1)
当totalHrsWkd
小于0时,程序无效的原因是以下代码创建了无限循环。
while ( totalHrsWkd < 0 )
{
System.out.printf( "Try again! Hours worked cannot be negative.");
System.out.printf( "Enter your hours worked including overtime: ");
}
您还应该阅读此循环中的工作小时数。