如何修复循环错误登录注销系统(无数据库)(也有关于会话时间的代码)



我创建了一个基本的登录和注销系统(无数据库(,使用为学校作业提供的唯一用户名,但我在while循环和会话时间方面遇到了问题。

我尝试将一组代码复制并粘贴到此主代码的不同部分,以便我可以得到预期的结果,但结果有点错误。我试图在互联网上搜索有关会话时间的信息,但我一无所获。

  while (login =  true){
      try {
          System.out.println("Enter your name:");
          String name = cue.nextLine();
          System.out.println("--------------------");
          System.out.println("");
          System.out.println("Date and Time of Login:");
          System.out.println(dtf.format(now));
          System.out.println("");
          System.out.println("--------------------");
          System.out.println();
          System.out.println("Enter your name to log out:");
          String logout = cue.nextLine();
          System.out.println("");
          if (logout.equals(name)){
              System.out.println("--------------------");
              System.out.println("");
              System.out.println("Date and Time of Logout:");
              System.out.println(dtf.format(now));
              System.out.println("Session Time:");
              /*can you also please tell me what code to tell the gap between the 
              login time and log out time?*/
              System.out.println("");
              System.out.println("--------------------");
              login = false;
            } else {
                login = true;
            }  
      } catch (Exception e){
          cue.nextLine();
      } finally{
          System.out.println("Do you want to register again? 0 for yes and 1 for no");
          int no = cue.nextInt();
          if (no==0) {
              login = true;
          } else if (no==1) {
                System.exit(1);
          } else {
              System.out.println("1 or 0 only!");
          }   
      }
}
  • 这必须是预期的输出:

如果名称正确:

Enter your name:
nmae
--------------------
Date and Time of login:
2019/02/03 16:38:46
--------------------
Enter your name to log out:
nmae
--------------------
Date and Time of logout:
2019/02/03 16:38:46
Session Time:
(This must show how many minutes and seconds a client uses the program)
--------------------
Do you want to register again? 0 for yes and 1 for no
0
Enter your name:

不正确,稍后会更正:

Enter your name:
name
--------------------
Date and Time of login:
2019/02/03 16:38:46
--------------------
Enter your name to log out:
nmae
Enter your name to log out:
name

但事实证明,在第二个循环、第三个循环等情况下,程序要求我"输入您的姓名注销"和"您要再次注册吗?0 表示是,1 表示否"。打印"输入你的名字"部分,而不是询问我的名字。

然后当我输入 0 退出时,此错误显示为C:UsersDELLAppDataLocalNetBeansCache10.0executor-snippetsrun.xml:111: The following error occurred while executing this line: C:UsersDELLAppDataLocalNetBeansCache10.0executor-snippetsrun.xml:94: Java returned: 1

要获得不同的 beetwen 登录时间和注销时间,您可以使用 java8 中的Duration类:

loginTime = LocalDateTime.now();
...
logoutTime = LocalDateTime.now();
Duration.between(loginTime, logoutTime).getSeconds();

您返回的错误级别为 1,这是程序终止向操作系统返回错误的方式。我无法测试,因为我不使用 Windows,但您可以尝试用 System.exit(0) 替换System.exit(1)

最新更新