开发者

comparing two string arrays to check if the entered value is there in the string array

开发者 https://www.devze.com 2023-02-19 10:58 出处:网络
I have two string arrays String[] Mids contains MSI MSU MSV String[] sl contains MSU MSV MSS Actual output should be

I have two string arrays

String[] Mids contains 
MSI
MSU
MSV

String[] sl contains
    MSU
    MSV
    MSS

Actual output should be

Action 
Action 
Action cannot be set

for(int i=0;i<sl.length;i++){
                for(int j=0;j<Mids.length开发者_运维问答;j++){
                    if((sl[i].equals(Mids[j]))){
                       System.out.println("Action");
                    }else{
                        System.out.println("Action cannot be set");
                    }
                }
            }

OUTPUT which i get

Action cannot be set
Action cannot be set
Action cannot be set
Action cannot be set
Action
Action cannot be set
Action
Action cannot be set
Action cannot be set


The problem is you're iterating over both arrays and always printing if you have found the same value. But you should do this only in the first loop. I changed the for loop:

for(int i=0;i<sl.length;i++){
   boolean found = false;
   for(int j=0;j<Mids.length;j++){
      if((sl[i].equals(Mids[j]))){
         found = true;
         break;
      }
   }

   if (found) {
      stdOut.println("Action");
   } else {
      stdOut.println("Action cannot be set");
   }
}


To say if an element is not found in an array you need to compare it with all the elements. Just because one comparison fails you cannot conclude that it is not found in the array.

Try something like:

for(int i=0;i<sl.length;i++){
        boolean found = false;
        for(int j=0;j<Mids.length;j++){
                if((sl[i].equals(Mids[j]))){
                        found = true;
                        break;
                }
        }
        if(found) {
                // print found.
        } else {
                // print not found.                                             
        }
}


Why don't you add another printline under the for loop(i) that displays s1 and mids so that you can better understand the execution?


Another way to do it, with fewer lines of code and fewer iterations would be:

List<String> midsList = new ArrayList<String>(Arrays.asList(Mids));
    for (String string : sl) {
        if (midsList.contains(string)) {
            System.out.println("Action");
        } else {
            System.out.println("Action cannot be set");
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消