gpt4 book ai didi

java - 带有嵌套 if/else 语句的 While 循环

转载 作者:搜寻专家 更新时间:2023-11-01 02:14:29 25 4
gpt4 key购买 nike

您好,我无法让我的程序正常运行。我能够清除任何语法错误,但现在我的输出已发出。

首先,在第一个IF语句中,提示人员同时输入姓名和部门,这样输出时name为空,只有department有输入。我认为这与整个 IF 语句有关,因为如果我将“字符串名称”更改为 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);
}
}

最佳答案

问题是

  employeeID = input.nextInt();

从输入流中读取下一个数字序列。但是,为了实际键入员工 ID,您还必须按 Enter 键。 Enter 按键仍在等待输入,因此当您下次调用

    String name = input.nextLine();

Scanner 类出现“哦,这是一个 Enter 按键,我猜用户想要一个空名称。”您甚至没有机会输入姓名,这就是为什么您的程序似乎同时询问两个问题(姓名和部门)。

如果您希望继续使用Scanner 类,我建议避免使用nextInt() 等方法并始终使用nextLine() 代替。当然,您必须使用类似的方法将用户键入的数字转换为 Java 整数 parseInt() .

关于java - 带有嵌套 if/else 语句的 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9384897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com