编程语言
首页 > 编程语言> > java – While循环使用嵌套的if / else语句

java – 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);
}
}

解决方法:

问题是

  employeeID = input.nextInt();

仅从输入流中读取下一个数字序列.但是,为了实际键入员工ID,您还必须按Enter键. Enter键仍在等待输入,所以下次通话时

    String name = input.nextLine();

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

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

标签:java,if-statement,while-loop,nested-loops
来源: https://codeday.me/bug/20190530/1184349.html