user210394
user210394

Reputation: 1

Checking If Values in Array Are Different Java

I've got this code:

@Override
public int compareTo(LargeInt passedIn)//
{
  if(passedIn == null)
  {   
     throw new RuntimeException("NullExceptionError");
  }   
  int ewu = 0;
  int avs = 0;

  if(this.myArray.length != passedIn.myArray.length)
  {   
     return this.myArray.length - passedIn.myArray.length;
  }
  for(this.myArray.length == passedIn.myArray.length)
  {



  }
  for(int x = 0; x < this.myArray.length; x++)
  {
     ewu += this.myArray[x];       
  }
  for(int x = 0; x < passedIn.myArray.length; x++)
  {
     avs += passedIn.myArray[x];
  }
  return ewu - avs;  

}

My goal is, under this line:

for(this.myArray.length == passedIn.myArray.length)

I want to If the lengths are equal, go through the array until a value that is different is found. Then subtract those two values and return. How might I go about doing this?

Upvotes: 0

Views: 63

Answers (2)

zapl
zapl

Reputation: 63955

You can do

public int compareTo(LargeInt passedIn)
{
    if (this.myArray.length != passedIn.myArray.length)
    {
        return this.myArray.length - passedIn.myArray.length;
    }
    for (int i = 0; i < this.myArray.length; i++) {
        if (this.myArray[i] != passedIn.myArray[i])
            return this.myArray[i] - passedIn.myArray[i];
    }
    return 0;
}

If the arrays are different lengths you've returned already. There is no point in checking whether they are the same length. And after you've checked for differences in the new loop, you can be sure that they are identical and skip those loops that sum up the arrays. They will have the same sum since they must be identical.

Upvotes: 1

jp-jee
jp-jee

Reputation: 1523

If the lengths are equal

so, why not use if(myArray.length == passedIn.myArray.length) instead of that (syntactically incorrect) for-loop? (In your case, it is just the elseof the condition before).

If the condition is true, iterate over the arrays as you did by the loops below.

Upvotes: 0

Related Questions