java - 在 Java 中中断 for 循环

标签 java arrays authentication

我需要帮助,我已经竭尽全力打破循环,但它一直显示 else 语句打印出来。我试图弄清楚如何通过数组进行登录,但我没有成功。悲伤。
主方法登录

 import java.util.*;


 public class LogIn {

public static void main(String[] args) {
    Person [] people = new Person[2];
    people[0] = new Person("Heather","Ward","Davis");
    people[1] = new Person("Thomas","Cummings","Tomc84");
    Scanner input = new Scanner(System.in);
    String current_login = "";
    String pass = "";
    int login_count = 3;


    //do{
        System.out.print("Enter your name: ");
        current_login = input.nextLine();
        System.out.print("\nEnter your password: ");
        pass = input.nextLine();
        outerloop:
        for (Person p: people){
            if(current_login.equals(p.getF_name())  && pass.equals(p.getPassword())){
                System.out.println("\nHello " + p.getF_name() + " " + p.getL_name());
                break outerloop;
            }
            else{
                login_count--;
                System.out.println("\nYou have " + login_count + " tries");
            }
        }

    //}while(login_count > 0 );


}
}

enter image description here

public class Person {
private String f_name = "";
private String l_name = "";
private String password = "";

public Person(){};

public Person(String f_name, String l_name, String password) {
    this.f_name = f_name;
    this.l_name = l_name;
    this.password = password;
}
public String getF_name() {
    return f_name;
}
public void setF_name(String f_name) {
    this.f_name = f_name;
}
public String getL_name() {
    return l_name;
}
public void setL_name(String l_name) {
    this.l_name = l_name;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}

public String toString(){
    return "first name: " + f_name +
            "Last name: " + l_name ;
}
}

最佳答案

也许不用乱用 break 语句,而是使用一个额外的 boolean 标志。

//Change if block to set the boolean flag
if(current_login.equals(p.getF_name())  && pass.equals(p.getPassword())){
                System.out.println("\nHello " + p.getF_name() + " " + p.getL_name());
                authenticated = true;
}

//Use it in your while statement
while(login_count > 0 && !authenticated);

关于java - 在 Java 中中断 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20873005/

相关文章:

java - 服务器浏览器,例如 Game-Monitor.com

Django 表单验证,将经过身份验证的用户作为字段

Java Nailgun 无法启动简单的 swing 应用程序

php - 在查询结果中将不同的数组合并为一个数组

arrays - 如何将范围作为数组从 Excel 导入 Word 文档

c - 使用 C 识别等差

authentication - 为什么当从外部源(即 Excel、Word 等)单击链接时,cookie 无法识别

spring - 使用Spring Security插件的Supervisor身份验证可在Grails中执行操作

Java 将 StringBuilder 转换为 CharBuffer

java - 函数不扩展到其他类