fr00ty_l00ps
fr00ty_l00ps

Reputation: 730

For Each block in Specific Context in Java

I am an eighth grader on a mission to create an application in Java that finds the point where two virtual lines meet, given the slope and y-intercept of the two lines. As it stands right now, I have two arrays (both with long values) that store the y values for the given x values (x = 0, 1, 2, etc). Now I need to figure out how to create a for each block (you know, the one with the colon in it) to check if the y value in the first array is equal to its counterpart in the other array. How do I do this?

Upvotes: 0

Views: 327

Answers (3)

Sully
Sully

Reputation: 14943

Edit

If you have both the x and y in arrays type Long just do

findIntersect:
  for(Long x : xArray){
    for(Long y : yArray){
      if(x==y){
        System.out.println("They do intersect");
        break findIntersect; //leave loop
      }
    }
  }

sorry for missing that part.

End edit

List<Long> xList; //Assuming it has 0, 1, 2, 3, 4, 5

for(Long x : xList){
  Long y1 = giveMePointYBasedOnSlope1(x);
  Long y2 = giveMePointYBasedOnSlope2(x);

  if(y1 == y2){
    System.out.println("They do intersect");
    break; //leave loop
  }
}

//Example slope1 :  y = (x * 2) + 3
public Long giveMePointYBasedOnSlope1(Long x){
  return (x*2) + 3;
}

//Example slope2 :  y = (x * -.5) + 7    
public Long giveMePointYBasedOnSlope2(Long x){
  return (x * -0.5) + 7;
}

Upvotes: 1

Puneet
Puneet

Reputation: 736

I'm not going to comment on the algorithm , but it seems like for your use case the for-each block isn't a good fit. Apart from the fact that for-each blocks don't lend themselves well to multiple collections, you potentially might also have the problem of arrays being of different sizes.

You are better off using a loop like the following

for(int i = 0;i < firstArr.length && i < secondArr.length;i++) {
  //Your comparison logic here
}

What this loop is doing is that it only goes until the end of the smaller of the 2 arrays.

Upvotes: 0

MByD
MByD

Reputation: 137382

As you have two arrays, you should probably use a normal loop, and not a for-each loop. Something like:

// assuming both arrays are of the same size
for (int i = 0; i < firstArr.length; ++i) {
    if (firstArr[i] == secondArr[i]) {
        // match found
    }
}

Upvotes: 1

Related Questions