gpt4 book ai didi

java - 在 Java 中中断 for 循环

转载 作者:行者123 更新时间:2023-11-29 09:43:53 25 4
gpt4 key购买 nike

我需要帮助,我已经竭尽全力打破循环,但它一直显示 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com