Dilyan
Dilyan

Reputation: 37

Comparing two arrays in java with for loop

I am having difficulties with this program. I have to compare the two arrays by reading the arrays from the console and after the user enters them, print a statement for whether or not they are true. I am not sure if I can use the compare function, but I have to do it with a for loop.

Here is what I have tried:

import java.util.Scanner;

@SuppressWarnings("unused")
public class TwoArrays {
    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Scanner input1 = new Scanner(System.in);
        System.out.println("enter the first array");
        String firstArrayAsString = input1.nextLine();

        System.out.println("enter the second array");
        String secondArrayAsString = input1.nextLine(); 

        if (firstArrayAsString. length() != secondArrayAsString.length()){
            System.out.println("false.arrays are not equal");       
        } else {
            int arrayLen = firstArrayAsString.length();
            char[] firstArray = firstArrayAsString.toCharArray();
            char[] secondArray = secondArrayAsString.toCharArray();

            int i = 0;
            while (i < arrayLen && firstArray[i] == secondArray[i]); {
                i++;
            }

            if (i == arrayLen) {
                System.out.println("true.they are equal");
            } else {
                System.out.println("False.they are not equal");
            }
        }
        input1.close();
    }
}

Upvotes: 1

Views: 19473

Answers (7)

user13782119
user13782119

Reputation: 314

Please find below code two compare array elements. The below code will not check remove duplicate or sorting or not compare arrays length.

Only focus on the array elements in a1,a2,a3 it will compare the array values like

  1. a1,a2 -> true
  2. a1,a3 -> false

sameElementfunction it return the flag either false or true

import java.util.Arrays;
import java.util.List;


public class SampleTest {

    public static void main(String[] args) {
        Integer[] a1 = {1,2,3,2,1};
        Integer[] a2 = {1,2,3};
        Integer[] a3 = {1,2,3,4};


        boolean result1 = sameElements(a1, a2);
        boolean result2 = sameElements(a1, a3);

        System.out.println(result1); // true
        System.out.println(result2);// false


    }

    public static boolean sameElements(Integer[] a, Integer[] b) {

        List<Integer> listA1=Arrays.asList(a);
        List<Integer> listB1=Arrays.asList(b);


        boolean flag = false;

        for(int i=0;i<a.length;i++){
           if(listB1.contains(a[i])){
               flag=true;
           }
           else{
               flag=true;
           }
        }


        for(int i=0;i<b.length;i++){
            if(listA1.contains(b[i])){
                flag=true;
            }
            else{
                flag=false;
            }
        }


        return flag;
    }

Upvotes: 0

Ibrahim Elsobkey
Ibrahim Elsobkey

Reputation: 1

BufferedReader existFile = new BufferedReader(
            new FileReader("D:/1.txt"));
    BufferedReader recievedFile = new BufferedReader(
            new FileReader("D:/2.txt"));
    String str, str1 = null;
    List<String> list = new ArrayList<String>();
    List<String> list1 = new ArrayList<String>();

    while ((str = existFile.readLine()) != null) {
        list.add(str);

    }
    while ((str1 = recievedFile.readLine()) != null) {
        list1.add(str1);
    }

    String[] stringArr = list.toArray(new String[list.size()]);
    String[] stringArr1 = list1.toArray(new String[list1.size()]);

    for (int i = 0; i < stringArr1.length; i++) {
        for (int j = 0; j < stringArr.length; j++) {
            if (stringArr1[i].equalsIgnoreCase(stringArr[j])) {
                System.out.println(stringArr1[i]);
            }
        }
    }

Upvotes: 0

AdamMc331
AdamMc331

Reputation: 16710

I would change this to use the charAt(int) function rather than changing the values to an array. Since you're reading them as strings, just compare them as strings, like this:

if(firstArrayAsString.length() != secondArrayAsString.length()){
   return false;
} else{
   for(int i = 0; i < firstArrayAsString.length(); i++){
      if(firstArrayAsString.charAt(i) != secondArrayAsString.charAt(i){
         return false;
      }
   }
   return true;
}

This first checks if the arrays are the same size. If they are not, we can already say they are not equal. If they are the same size, loop through and make sure the character at each index matches. If at any point we find characters that don't match, we know it is not equal. If we loop through the entire thing without finding a difference, then the two arrays are equal.

I would like to add, though, that if it's not required to use a for loop, why not just use:

firstArrayAsString.equals(secondArrayAsString);

to compare the two string values?

Minor Edit

Rereading your question I see that you said you can't use the equals method, but I am choosing to leave this in my answer as a possible alternative for future readers.

Upvotes: 0

Naman Gala
Naman Gala

Reputation: 4692

Try this code.

char[] firstArray = {'a', 'b', 'c'};
char[] secondArray = {'a', 'b', 'c'};

if (firstArray.length != secondArray.length) {
    System.out.println("False.they are not equal");
} else {
    boolean isEqual = true;
    for (int i = 0; i < firstArray.length; i++) {
        if (firstArray[i] != secondArray[i]) {
            System.out.println("False.they are not equal");
            isEqual = false;
            break;
        }
    }
    if (isEqual)
        System.out.println("true.they are equal");
}

Upvotes: 2

Scary Wombat
Scary Wombat

Reputation: 44844

Your problem is this code

while (i < arrayLen && firstArray[i] == secondArray[i]); {

has a semicolon at the end; // remove it

Plus as mentioned before

if (i == arrayLen) {

should be

 if (i == arrayLen - 1) {

Note

The warnings that you surpressed using

@SuppressWarnings("unused") 

was probably telling you something useful.

Upvotes: 0

Slim_user71169
Slim_user71169

Reputation: 866

 int i = 0;
 while (i < arrayLen && firstArray[i] == secondArray[i]); {
 i++;
 }

Change this to below:

boolean isEqual = true;
for(int i=0;i<arrayLen;i++){
  if(firstArray[i]!=secondArray[i]) {
  isEqual = false;
  break;
  } 
}

Finally, you can show result with flag 'isEqual'

if(isEqual) System.out.println("Equal");
else System.out.println("Not Equal");

Upvotes: 0

Fuuka Adachi
Fuuka Adachi

Reputation: 23

boolean isEqual = true;

for(int i=0;i<arrayLen;i++){
    if(firstArray[i] != secondArray[i]){
        System.out.println("False.they are not equal");
        isEqual = false;
        break;
    }
}
if(isEqual){
    System.out.println("true.they are equal");
}

If that not work, try to change (firstArray[i] != secondArray[i]) to (!(firstArray[i].equals(secondArray[i]))) or st like that.

Upvotes: 0

Related Questions