接受输入并将其与多维数组(Java)的值进行比较

时间:2018-12-03 22:10:55

标签: java multidimensional-array user-input boolean-operations

public class ZooManagement {

    static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {

    String[][] employeeInfo = {{"bob", "ross"}, {"timmy", "turner"}, {"red","forman"}};

    System.out.println("Welcome to your Zoo Employee Tool!");
    System.out.println("Please enter your employee id.");
    String id = keyboard.nextLine();
    System.out.println("Please enter your password.");
    String password = keyboard.nextLine();

这是我现在正在使用的代码的摘录。基本上,我的目标是获取用户输入并将idpassword的值与employeeInfo[][]数组中列出的值进行比较,同时如果匹配项为boolean,则使用布尔变量作为标志找到了。我对Java和编程一般还是很陌生,因此任何建议都将大有帮助!

1 个答案:

答案 0 :(得分:-1)

public class ZooManagement
{
    public static void main(String[] args)
    {

        final String[][] employeeInfo = {{"bob", "ross"}, {"timmy", "turner"}, {"red","forman"}};
        boolean flag = false;

        Scanner scanner = new Scanner (System.in);

        System.out.print("Please enter username:  ");
        String username = scanner.next();
        System.out.println();

        System.out.print("Please enter password:  ");
        String password = scanner.next();
        System.out.println();

        for(int row = 0;  row < employeeInfo.length;  row++)
        {
            for(int column = 0; column < employeeInfo[row].length; column++)
            {
                if(employeeInfo[row][0].equals(username)  &&  employeeInfo[row][1].equals(password))
                {
                    flag = true;
                }
            }
        } 

        if(flag)
        {
            System.out.print("Successful login");
        } 
        else
        {
            System.out.print("Invalid username or password");
        } 
    } 
}