简体   繁体   English

在Java中中断循环

[英]break for loop in java

I need help, I have tired all I can to break the loop but it keeps displaying the else statement print out. 我需要帮助,我已经竭尽全力打破循环,但是它一直显示出else语句。 I am trying to figure out how to make a log in through an array and I have not been successful. 我试图弄清楚如何通过数组进行登录,但没有成功。 SAD. 伤心。
main method login 主要方法登录

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


}
}

在此处输入图片说明

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

Maybe instead of mucking around with the break statement, use an extra boolean flag. 也许不要使用break语句,而应使用一个额外的布尔标志。

//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);

For each person in your "DB" you are saying that, if the username and password are not correct, means that the user entered wrong credentials. 对于您“数据库”中的每个人,您说的是,如果用户名和密码不正确,则表示用户输入了错误的凭据。 That's wrong. 错了 You have to search the entire DB before saying "You have n tries". 您必须先搜索整个数据库,然后说“您有n次尝试”。

Your code should be 您的代码应为

    boolean found = false;
    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());
            found = true;
            break;
        }
    }

    if(!found){
        login_count--;
        System.out.println("\nYou have " + login_count + " tries");
    }

Or, if you don't like it: 或者,如果您不喜欢它:

    boolean found = false;
    for (Person p: people){
        if(current_login.equals(p.getF_name())  && pass.equals(p.getPassword())){
            found = true;
            break;
        }
    }

    if(found){
        System.out.println("\nHello " + p.getF_name() + " " + p.getL_name());
    }
    else{
        login_count--;
        System.out.println("\nYou have " + login_count + " tries");
    }

It's just your loop logic that's broken. 只是循环逻辑被破坏了。 It looks like what you're trying to do is loop through the people array and if no element has the specified login, do what you have in the else. 看起来您想要做的是遍历people数组,如果没有元素具有指定的登录名,请执行其他操作。 But what your loop actually does is do the else for every element in the array that's not the specified login (until it finds a correct one). 但是您的循环实际上所做的是对未指定登录名的数组中的每个元素执行else操作(直到找到正确的登录名)。

I think what you are looking for is something like this: 我认为您正在寻找的是这样的:

Person user = null;
for(Person p : people) {
    if(current_login.equals(p.getF_name()) && pass.equals(p.getPassword())) {
        user = p;
        break;
    }
}

if(user != null) {
    System.out.println("\nHello " + user.getF_name() + " " + user.getL_name());

} else { // do false action when 'not found'
    login_count--;
    System.out.println("\nYou have " + login_count + " tries");
}

Or similarly, you can put this in its own method to make the logic simpler (but you would have to change people so it's a static field instead of a variable declared in main or add a parameter for it): 或者类似地,您可以将其放在自己的方法中以简化逻辑(但是您必须更改people因此它是一个静态字段,而不是在main中声明的变量或为其添加参数):

static Person getUserForLogin(String name, String pass) {
    for(Person p : people) {
        if(name.equals(p.getF_name()) && pass.equals(p.getPassword())) {
            return p;
        }
    }
    return null; // do false action when 'not found'
}

Then you say: 然后你说:

Person user = getUserForLogin(current_login, pass);
if(user != null) {
    System.out.println("\nHello " + user.getF_name() + " " + user.getL_name());

} else {
    login_count--;
    System.out.println("\nYou have " + login_count + " tries");
}

Your methods getFname and getPassword must first return the first name and password for person[0] then return the username and password for person[1]. 您的方法getFnamegetPassword必须首先返回person [0]的名字和密码,然后返回person [1]的用户名和密码。 What you want to do is create a method which checks if the username or and password matches either of the two person objects, eg; 您想要做的是创建一个方法,该方法检查用户名或密码是否与两个人对象之一匹配,例如;

public boolean authenticate(String username, String password) {
    for(Person person : people) {
        if(username.equals(person.getF_name) && password.equals(person.getPassword()))
            return true;
    }
    return false;
}

The problem lies with your of all of the members of the Person array people . 问题出在Person阵列people的所有成员中。 Since it's iterating through all of the elements, it will always first check the name and password of Heather Ward first, so you'll hit the else. 由于它遍历所有元素,因此始终将始终首先检查Heather Ward的名称和密码,因此您将按其他步骤进行操作。 You could change the if-else construct to something like: 您可以将if-else构造更改为类似以下内容:

for(Person p: people)
{
    if(current_login.equals(p.getF_name()))
    {
        if(pass.equals(p.getPassword())){
            System.out.println("\nHello " + p.getF_name() + " " + p.getL_name());
            break;
        }
        else{
            login_count--;
            System.out.println("\nYou have " + login_count + " tries");
        }
    }
    // no else at this level, we just want to see if the name exists in
    // our array.
    // If not, just continue the loop, don't give an error if the current
    // Person doesn't match!
}

Of course this will only reduce the number of tries (and display the warning) when you enter a correct first name but incorrect password, but it's a starting point. 当然,这只会减少您输入正确的名字但密码错误时的尝试次数(并显示警告),但这只是一个起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM