通过索引“ Java”彼此相等的两个数组

时间:2018-10-23 12:35:56

标签: java arrays

如果用户在运行该程序后Sully输入了自己的姓名,则该程序应输出

  

您好,您好,Sully是经理!

但是正在发生的是,程序将打印出Sully是管理者,并将继续将Sully与数组中的其他值进行比较。我只是在用Java学习数组。

    public class Aconstructors {

        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in) ;
            String user ;
            String [] empName , empPos ;
            empName = new String [2] ;
            empName [0] = "Sully" ;
            empName [1] = "John" ;
            empPos = new String [2] ;
            empPos [0] = "Manager" ;
            empPos [1] = "Employ" ;

            System.out.println("Enter Your Name to know Your Position : ");
            user = scan.nextLine()  ;

            for (int i = 0 ; i <empName.length;i++ ) {
                //check if user input is equals
                if (empName[i].equals(user)) {
                    // indexes are equals
                    empName.equals(empPos.length );
                    System.out.printf("Hello %s you are %s !!\n",empName[i],empPos[i]);
                    // if user input is not equal
                }
                else if   (!empName[i].equals(user))  {
                    System.out.println("unknowing user !! ");
                }
            }
        }
    }

John的输出:

Enter Your Name to know Your Position : 
John
unknowing user !! << as you see here java checking the values 
Hello John you are the Employ  !! << java found John 

Sully的输出:

Enter Your Name to know Your Position : 
Sully
Hello Sully you are Manager !! << found Sully 
unknowing user !! << didnt stop  

2 个答案:

答案 0 :(得分:0)

尝试改善

之类的for循环
for (int i = 0 ; i <empName.length;i++ ) {
            //check if user input is equals
            if (empName[i].equals(user)) {
                // indexes are equals 
                System.out.printf("Hello "+empName[i]+" you are "+empPos[i]);
                break;
                // if user input is not equal
            } else if   (!empName[i].equals(user))  {
                System.out.println("unknowing user !! ");
            }
        }

您只需要将您的用户输入与empName数组进行比较,并打印该员工的职位就非常简单,因为两者的索引都相同,如果找到匹配项,则使用break来打破循环。

答案 1 :(得分:0)

在循环之前声明一个布尔变量const CREATE_ACCOUNT_STATEMENT = 'INSERT INTO `Accounts` (`account_token`, `account_name`) VALUES (?, ?)' try { mysqlConnectionPool.execute(CREATE_ACCOUNT_STATEMENT, [ account_token, account_name ]) .then(() => { res.end(JSON.stringify({ token: account_token })) }) .catch((e) => { debug(1, "error while trying to create account:", e) res.status(500).end("Internal Server Error") }) } catch(e) { debug(1, "error while trying to create account:", e) res.status(500).end("Internal Server Error") } ,以检查名称是否存在于列表中。如果在列表中找到该名称,请更改unknown=true;
当循环结束时,如果变量未更改(表示名称不在列表中),则显示消息“未知”。

unknown=false;