1

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();
    }
}
7
  • 2
    so what is your question? The above code may work (not elegant though) if you change i == arrayLen -1 Commented Nov 11, 2014 at 4:59
  • It works but doesn't print(atl east on my eclipse) true or false.So why is that happening? Commented Nov 11, 2014 at 5:01
  • what does it print? Does it throw an exception? Commented Nov 11, 2014 at 5:02
  • why are you not using equals method in Arrays class? boolean isEqual = Arrays.equals(firstArray,secondArray); Commented Nov 11, 2014 at 5:02
  • @MadProgrammer or even String.equals Commented Nov 11, 2014 at 5:03

7 Answers 7

2

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm glad OP understood this enough to accept it, but someone who's new to programming might not understand your copy and paste code.
I just want to know the reason for down vote. So that I can keep in mind for next time.
0
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.

Comments

0
 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");

Comments

0

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.

Comments

0

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.

Comments

0
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]);
            }
        }
    }

Comments

0

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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.