2013-10-27 3 views
-2

내 코드는 로봇의 y 좌표와 대상의 y 좌표를 비교하기위한 것입니다. 인쇄 문을 추가 할 때 함수에서 아무 것도 반환하지 못하는 문제가 있습니다.이 문제는 괄호로 처리해야한다는 느낌이 들지만 정확히 어떻게 사용하는지 모르겠습니다.Java에서 "도달 할 수없는 문"및 "없는 경우"를 피하는 방법은 무엇입니까?

이것은 전체 프로그램은 아니지만 오류가있는 유일한 비트입니다.

나는 이것을 컴파일하려고하면 :

public class Ex12 
{ 

    private byte isTargetNorth(IRobot robot) 
    { 

     if (robot.getLocationY() > robot.getTargetLocation().y) { 

      return 1; System.out.println("north"); 

     } else if (robot.getLocationY() == robot.getTargetLocation().y) { 

      return 0; System.out.println("no"); 

     } else { 

      return -1; System.out.println("south"); 

     } 

    } 
} 

내가 얻을 오류 : 연결할 수없는 문

내가하려고하면이 :

public class Ex12 
{ 

    private byte isTargetNorth(IRobot robot) 
    { 

     if (robot.getLocationY() > robot.getTargetLocation().y) 

      return 1; System.out.println("north"); 

     else if (robot.getLocationY() == robot.getTargetLocation().y) 

      return 0; System.out.println("no"); 

     else 

      return -1; System.out.println("south"); 

    } 
} 

내가 얻을 오류 : '다른'없는 '경우 '

System.out.println() 함수를 제거 할 때 오류가 발생하지 않습니다.

+0

'isTargetNorth'라는 이름의 메소드는 실제로 'boolean'유형의 값을 반환하고 'byte'는 반환하지 않아야합니다. –

+1

메시지의 어떤 부분을 이해하지 못합니까? – SLaks

+0

@RohitJain : 여기 최악의 상황과는 거리가 멀죠? –

답변

2

return 문은 메서드를 끝냅니다. 그래서 System.out은 절대로 호출되지 않습니다.

+0

나는 그것을 몰랐다. 고마워. –

1

첫 번째 것은 각각 System.out.println 호출 - return이 현재 메소드를 종료 한 후 return 문을 이동하므로 System.out.println이 호출되지 않으므로 도달 할 수 없습니다.

두 번째는 혼란 형식의 경우입니다 : 코드

if (robot.getLocationY() > robot.getTargetLocation().y) 
    return 1; System.out.println("north"); 
else if ... 
//... 

예 당신이 조심해야하는 이유의 좋은 알림 경우없이

if (robot.getLocationY() > robot.getTargetLocation().y) { 
    return 1; 
} 
System.out.println("north"); 
else if ... //else without if right here, because else should follow immediately after an if block! 

그렇지 않으면 실제로 동일합니다 중괄호를 생략 할 때.

0

첫 번째 코드 블록에는 도달 할 수 없도록하는 return 문 뒤에 System.out.println이 있습니다. return 문 앞에 System.out.println을 추가하면 작동합니다.

두 번째 예에서는 if 문에서 bocks ({...})를 제거 했으므로 조건 당 하나의 명령문 만 가질 수 있습니다. 당신은 두 반환 및 System.out.println 있습니다.

0

당신이 쓴 :

return 1; 
System.out.println(""); // << This is written after you return to the calling method. 

이 의미, 여기에 코드를 작성할 수 없습니다. 당신이 반환 값을 반환 한 후

  1. 코드를 작성하지 마십시오 :

    은 다른 코드에서 당신은 당신의 문제를 해결하기 위해
    if() Some Code; 
    // This statement will be executed, because it is outside of the if-block 
    else 
        // The else above has no if. 
    

    을 썼다.
  2. 괄호를 쓰면 {} 쓸 것이지만, 언제나 블록을 볼 수 있습니다.