循环永远持续下去

时间:2017-11-05 20:27:07

标签: java loops for-loop file-io while-loop

我的代码遇到了一些问题。我正在尝试从用户那里获取用户名和密码,并读取包含多个用户名和密码的文件。如果用户名和密码不在同一行,则用户再尝试2次,否则程序将退出。目前,即使用户输入正确的信息,代码也说用户名和密码错误,并且提示用户超过3次。有人可以帮忙吗?我有下面的代码。我没有发布标题,因为我觉得它可能有点令人困惑。谢谢!

//*****Prompts user to enter in user name and password
    System.out.println("Please enter in your user name: ");
    userName = keyboard.nextLine();
    System.out.println("Please enter in your password: ");
    password = keyboard.nextLine();
    while (userName.equals("done"))
    {
      System.out.println("You entered done. Now exiting the test");
      System.exit(0);
    }

    while (userInfoScanner.hasNext())
        {
          String userInfoLine = userInfoScanner.nextLine();
          String [] userInfoArr = userInfoLine.split ("\t");
          // for (int i=0; i<3; i++)
          //{ 
          if(userInfoArr[0].equalsIgnoreCase(userName) && userInfoArr[1].equals(password))
          {
            System.out.println("Correct");
          }
          while (!userInfoArr[0].equalsIgnoreCase(userName) && !userInfoArr[1].equals(password))
          {
            for (int i=0; i<3; i++)
            {
              System.out.println();
              System.out.println("Incorrect. Please enter in the correct user name: ");
              userName = keyboard.nextLine();
              System.out.println("Please enter in the correct password: ");
              password = keyboard.nextLine();
            }
          }
        }

1 个答案:

答案 0 :(得分:0)

while (userInfoScanner.hasNext())循环取决于用户输入,但是用户可以总是写一些东西,所以这个while循环将是永远的。

您可以写一些简短的内容。

Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter in your user name: ");
        String userName = keyboard.nextLine();
        System.out.println("Please enter in your password: ");
        String password = keyboard.nextLine();

        while (userName.equals("done"))
        {
            System.out.println("You entered done. Now exiting the test");
            System.exit(0);
        }

        System.out.println("Enter login and password");
        String userInfoLine = keyboard.nextLine();
        String [] userInfoArr = userInfoLine.split (" "); // i changed separation from \t to simple space

        if(userInfoArr[0].equalsIgnoreCase(userName) && userInfoArr[1].equals(password))
        {
            System.out.println("Correct");
        }
        while (!userInfoArr[0].equalsIgnoreCase(userName) && !userInfoArr[1].equals(password))
        {

            System.out.println();
            System.out.println("Incorrect. Please enter in the correct user name: ");
            userName = keyboard.nextLine();
            System.out.println("Please enter in the correct password: ");
            password = keyboard.nextLine();

        }