while循环和字符串比较我的密码程序

时间:2013-09-04 20:58:57

标签: java string loops while-loop comparison

我正在尝试做一个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;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

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

否则,代码问题在于,由于控制流中遇到“return”或“break”,循环在第一次迭代后永远不会继续。

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

请告诉我们,目标是什么;我们可以帮到你更多。

答案 1 :(得分:0)

试试这个:

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 :(得分:0)

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

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");
}

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