0

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?

3
  • 1
    What is the purpose of this if(passedIn == null) { throw new RuntimeException("NullExceptionError"); }? If you check for null just to throw an Exception, then just remove that check. You'll get your desired NullPointerException if the variable is null "automatically". Commented Nov 22, 2014 at 0:16
  • Explain your for(this.myArray.length == passedIn.myArray.length) loop. Commented Nov 22, 2014 at 0:19
  • 1
    You already know how to use a for so just use another one and use if (myArray[x] != passedIn.myArray[x]) { } inside. Commented Nov 22, 2014 at 0:20

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.