跳出一段时间循环

时间:2015-07-29 13:21:49

标签: java loops while-loop

我的while循环出了问题。

如果while循环条件为false(when the password is wrong),则可以正常工作,但如果密码正确,则会同时写入You are logged inWrong password

我明白为什么会这样做,但我不明白如何解决问题。我需要使用while循环,因为它是一个需要它的学校作业。

import java.util.Scanner;
public class Password {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);

        String rightPassword = "Hello123";

        System.out.println("Write your password: ");
        String scan = scanner.nextLine();

        while(scan.equals(rightPassword)){
            System.out.println("You are logged in");
            break;
        }
        System.out.println("Wrong password");
    }

}

4 个答案:

答案 0 :(得分:1)

你应该做的是:

import java.util.Scanner;
public class Password {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String rightPassword = "Hello123";
        String scan="";
        while(true){
             System.out.println("Write your password: ");
             scan = scanner.nextLine();
             if(scan.equals(rightPassword)) {
                 System.out.println("You are logged in");
                 break;         
             } else {
                 System.out.println("Wrong password");
             }
        }
    }
}

在我们这样做的过程中,我们有一个无尽的for循环,在你提供正确的密码之前不会破坏。你可以添加一些尝试次数作为破坏条件。

根据评论I know, it become a infinite loop and that's why i use break. My requirement is that i must use a While loop. I know how to use a if-loop to solve the problem.您的解决方案应如下所示:

import java.util.Scanner;
public class Password {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String rightPassword = "Hello123";
        System.out.println("Write your password: ");
        while(!rightPassword.equals(scanner.nextLine())) {
            System.out.println("Wrong password");
            System.out.println("Write your password: ");
        }
        System.out.println("You are logged in");
    }
}

答案 1 :(得分:0)

您可以使用以下代码。

    int a=1;
    Scanner scanner = new Scanner(System.in);

    String rightPassword = "Hello123";

    System.out.println("Write your password: ");
    String scan = scanner.nextLine();

    while(scan.equals(rightPassword)){
        System.out.println("You are logged in");
        a=0;
       break;
    }
    if(a==1){
        System.out.println("Wrong password");
    }

答案 2 :(得分:0)

library(sqldf)

#Example to return 3rd lowest population of a State
result <-sqldf('Select City,State,Pop from data order by Pop limit 1 offset 2;')

#Note the SQL query is a sample and needs to be modifed to get desired result.

答案 3 :(得分:0)

你可能会有一些事情倒退。检查密码是否错误,而不是正确的密码,并再次询问密码。这样,您将从系统收到一条消息,这是一个错误的密码,或者一旦他们“成功登录”就会收到一个好的密码。

whitelisting