gpt4 book ai didi

JAVA扫描器在if/else语句中输入字符串

转载 作者:行者123 更新时间:2023-12-01 13:15:57 25 4
gpt4 key购买 nike

您好,我正在编写一个简单的用户名/密码输入,但我的代码绕过所有 if/if else 语句并转到 else 语句。我不确定我的语法是否不正确或者使用 if/else 语句是否不正确。或者如果我只是编码错误。请帮忙!

import java.util.Scanner;

public class Passwords
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] username = {"admin1", "admin2", "admin3", "admin4", "admin5"};
String[] password = {"pass1", "pass2", "pass3", "pass4", "pass5"};
System.out.println("Please enter in one of the following usernames : admin1, admin2, admin3, admin4, or admin5");
String userinput = input.nextLine();
System.out.println("Please enter in the password corresponding to your username: pass1, pass2, pass3, pass4, or pass5");
String passinput = input.nextLine();
if (userinput == username[0] && passinput == password[0])
{
System.out.println("Access granted!");
}
else if (userinput == username[1] && passinput == password[1])
{
System.out.println("Access granted!");
}
else if (userinput == username[2] && passinput == password[2])
{
System.out.println("Access granted!");
}
else if (userinput == username[3] && passinput == password[3])
{
System.out.println("Access granted!");
}
else if (userinput == username[4] && passinput == password[4])
{
System.out.println("Access granted!");
}
else
{
System.out.println("Sorry the username or password you entered is incorrect. Please try again");
System.out.println("Please enter in one of the following usernames : admin1, admin2, admin3, admin4, or admin5");
String userinput1 = input.next();
System.out.println("Please enter in the password corresponding to your username: pass1, pass2, pass3, pass4, or pass5");
String passinput1 = input.next();
if (userinput1 == username[0] && passinput1 == password[0])
{
System.out.println("Access granted!");
}
else if (userinput1 == username[1] && passinput1 == password[1])
{
System.out.println("Access granted!");
}
else if (userinput1 == username[2] && passinput1 == password[2])
{
System.out.println("Access granted!");
}
else if (userinput1 == username[3] && passinput1 == password[3])
{
System.out.println("Access granted!");
}
else if (userinput1 == username[4] && passinput1 == password[4])
{
System.out.println("Access granted!");
}
else
{
System.out.println("Sorry, your username/password does not match our database. Contact the administrator.");
}
}
}
}

最佳答案

use, userinput.equals(username[0])//这将比较字符串值

在 java 中 == 将比较对象 ID,如果它们是不同的对象,则始终为 false。

关于JAVA扫描器在if/else语句中输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22471114/

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