【问题标题】:While loops and string comparisons for my password program我的密码程序的while循环和字符串比较
【发布时间】:2013-09-08 12:57:49
【问题描述】:

我正在尝试做一个 while 循环,如果密码正确则打印欢迎语句,如果密码错误则拒绝您。当你错了,我希望它重新提出问题。不幸的是,当密码错误时,它只会发送垃圾邮件并且不会重新循环。谢谢!

import java.util.Scanner;

public class Review {
    public static void main(String[] args) {

        Scanner userInput = new Scanner(System. in );
        System.out.println("Enter user password");
        String userGuess = userInput.nextLine();
        int x = 10;

        while (x == 10) {

            if (userGuess.equals("test")) {
                System.out.println("Welcome");
                return;
            } else if (!userGuess.equals("test")) {
                System.out.println("Wrong, try again");
                break;
            }
        }
    }
}

【问题讨论】:

  • else if 中删除break。并将else if 替换为else
  • else if (!userGuess.equals("test")) 那时你已经知道userGuess != "test",所以只需使用else
  • 好的,我做到了。程序仍然会在 else 语句中发送垃圾邮件
  • 已修复。刚刚添加了“userGuess = userInput.nextLine();”在 else 语句中
  • 这可能不是正确的解决方法。

标签: java string loops while-loop comparison


【解决方案1】:

试试这个:

import java.util.Scanner;

public class Review {
    public static void main (String[]args) {

        Scanner userInput = new Scanner(System.in);

        while (true) {

            System.out.println("Enter user password");
            String userGuess = userInput.nextLine();

            if (userGuess.equals("test")) {
                System.out.println("Welcome");
                return;
            }

            else{
                System.out.println("Wrong, try again");
            }

        }
    }
}

我使用了 while(true) 而不是你做的 x=10 的事情。我将要求输入密码的部分移到了 while 循环内。您也可以将 userInput 声明移动到循环内部,如果您唯一使用它的时间是您要求输入密码时。

【讨论】:

    【解决方案2】:

    我认为您正在尝试创建一个解决方案,该解决方案检查 10 次密码然后退出。如果是这样,我会推荐 McGee 的前进方式。

    否则,您的代码的问题是由于在控制流中遇到“返回”或“中断”,循环将永远不会在第一次迭代后继续。

    即使这是固定的(可能是通过删除其中任何一个);程序将进入无限循环;因为 while 循环将有一个真实的情况(x == 10)。

    请告诉我们,目标是什么;我们可以为您提供更多帮助。

    【讨论】:

      【解决方案3】:

      您需要在循环内进行猜测。代码越少越好:

      Scanner userInput = new Scanner(System.in);
      System.out.println("Enter user password");
      for (int n = 0; n < 10; n++) {
          if (userInput.nextLine().equals("test")) {
              System.out.println("Welcome");
              return;
          }
          System.out.println("Wrong, try again");
      }
      

      通常,当您消除不必要的代码时,清晰度会提高。就是这样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-09
        相关资源
        最近更新 更多