简体   繁体   中英

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();
    }
}
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.

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

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM