2016-06-03 6 views
0

예외 처리가 예상대로 작동하면 원하는 무슨 달성해야 다음 코드 :스트림을 사용하여 이것을 작성하는 적절한 방법은 무엇입니까?

XVector position = new XVector(); 
IntStream.range(0, desired_star_count).forEach(a -> { 
    // Try to find a position outside the margin of other stars. 
    try 
    { 
     IntStream.range(0, XStarField.patience).forEach(b -> { 
      position.random(size); 
      error: 
      { 
       for (XVector point : this.positions) 
        if (position.sub(point).get_magnitude() < min_star_margin) 
         break error; 
       throw new XStarField.Found(); 
      } 
     }); 
    } 
    catch (XStarField.Found event) 
    { 
     this.positions.add(position.copy()); 
     this.colors.add(Math.random() < 0.5 ? XColor.RED : XColor.BLUE); 
    } 
}); 

불행하게도, 다음과 같은 두 가지 오류가 생성됩니다

Error:(33, 25) java: unreported exception XStarField.Found; must be caught or declared to be thrown 
Error:(37, 13) java: exception XStarField.Found is never thrown in body of corresponding try statement 

나는 동일한 코드를 작성한다면

position = XVector() 
for a in range(desired_star_count): 
    for b in range(self.patience): 
     position.random(size) 
     for point in self.positions: 
      if abs(position - point) < min_star_margin: 
       break 
     else: 
      self.position.append(position.copy()) 
      self.colors.append(XColor.RED if random.random() < 0.5 else XColor.BLUE) 
      break 

이것은 스트림을 사용하지 않고 쓸 간단 할 것입니다,하지만 난이 고려 : 파이썬, 아마 다음과 같이 밝혀 질 것입니다 그들을 더 잘 이해하는 학문적 학습 운동. 계수 루프를 대체하고 시도 된대로 해당 위치에서 스트림을 사용하는 코드를 작성하는 방법이 있습니까?

+0

'오류'라는 이름의 블록의 목적은 무엇입니까? – Michael

+0

'break error;'가 실행될 때 이것은'star'의 현재 값이 다른 별의 최소 여백 안에 있기 때문에 사용할 수 없다는 것을 의미합니다. 'break error;'가 실행되지 않으면,'throw new XStarField.Found();'는 이벤트 (예외) 핸들러에 의해 실행되고 잡히게된다. 이 시점에서,'position'의 값은 받아 들여질 수있는 것으로 알려져 있습니다. –

+0

좋습니다. 비록 직접적인 관련이 없지만, [질문] (http://stackoverflow.com/questions/33590916/idiomatic-way-of-traversing-image-functionally)의 답변은이 상황에서 약간의 빛을 비추는 초기 도움을 게시했습니다 – Michael

답변

0

대신 다음 코드를 사용할 수 있습니다. 구현시 예외 및 중단을 피할 수 있습니다. 스트림을 적절히 적용하면 알고리즘을 읽고 이해하기가 더 쉬워집니다.

XVector position = new XVector(); 
IntStream.range(0, DESIRED_STAR_COUNT).forEach(a -> { 
    // Try to find a position outside the margin of other stars. 
    IntStream.range(0, PATIENCE).filter(b -> { 
     position.random(size); 
     return !this.positions.stream().anyMatch(point -> position.sub(point).getMagnitude() < MIN_STAR_MARGIN); 
    }).findFirst().ifPresent(b -> { 
     this.positions.add(position.copy()); 
     this.colors.add((XColor) XRandom.sChoice(RED_STAR, BLUE_STAR)); 
    }); 
}); 
관련 문제