2016-12-03 1 views
0

일련의 교차하는 날씨 패턴 이후 트리의 높이를 예측하는 해커 랜 크 알고리즘 시도를 시도하고 있습니다. 왜 내 논리가 작동하지 않는 지 모르겠다. Java는 내 switch 문에서 중단 점이 작동하지 않는다고 말합니다. 나는 아래의 코드를 풀로 붙였다.Java : 모듈러스 연산자를 사용하는 스위치의 도달 할 수없는 문

import java.util.Scanner; 

public class Main { 

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    int i = scan.nextInt(); // user input how many test cases 
    System.out.println("test cases set."); 
    int[] cycles = new int[i]; 

    for (int x = 0; x < i; x++) { 
     cycles[x] = scan.nextInt(); // user input test cycles 
    } 


    for (int x = 0; x < i; x++) { 
     System.out.println(cycles[x]); 
     int temp = predictor(cycles[x]); 
     System.out.println(temp); 
    } 
} 


public static int predictor(int cycles) { 
    // determines the remainder to find even or odd cycle year 
    int heightRemainder = cycles % 2; 

    switch (heightRemainder) { 
     case 0: 
      System.out.println("Even number"); 
      return cycles; // UNREACHABLE, cycles is a temp variable to check functionality 
      break; 


     case 1: 
      System.out.println("Odd number"); 
      return cycles; // UNREACHABLE, same here 
      break; 
    } 
    return -1; 
    } 
} 
+0

각 break 문 바로 앞에 return 문이 있습니다. break 문을 실행할 방법이 없습니다. –

+0

프로그램 실행 후 * return 문 * 다음에 끝나기 때문에 * return 문 뒤에있는 코드는 의미가 없습니다 –

+0

return 문이'switch'에서 사용될 때 일반적으로'break'를 사용할 필요가 없습니까? @PatriciaShanahan 귀하의 도움에 감사드립니다! :) – Pahjay

답변

0

예, break 문이 return 문 뒤에 있기 때문에 작동하지 않습니다. 실행 제어가 break 문으로 이동하지 않습니다. 대신에 예측 방법이

public static int predictor(int cycles) { 
// determines the remainder to find even or odd cycle year 
int heightRemainder = cycles % 2; 
int r=-1; 


switch (heightRemainder) { 
    case 0: 
     System.out.println("Even number"); 
     r =cycles; 
     break; 


    case 1: 
     System.out.println("Odd number"); 
     r=cycles 
     break; 
    } 
    return r; 
    } 
} 
0

같은주기 값을 저장하고있어서의 단부에 그 변수를 반환하는 스위치 케이스를 사용 변수 복귀

: 브레이크를 제거; 문 ... 순환 값을 반환하기 때문에 코드가 누락되었습니다.

switch (heightRemainder) { 
     case 0: 
      System.out.println("Even number"); 
      return cycles; // UNREACHABLE, cycles is a temp variable to check functionality 
      case 1: 
      System.out.println("Odd number"); 
      return cycles; // UNREACHABLE, same here 
    } 
관련 문제