2016-06-20 2 views
-3

Java 프로그래밍 언어를 처음 사용하는 사람입니다. 그래서 나는 샘플 프로그램을 시험해 보았다. (예 : Enum Comparison with Switch-Case Statement). 위의 프로그램은 내가 1 케이스 (i.e:- Case Google:)에서 break 키워드를 놓친 것을 알 수 있습니다 보면 다음Java - Enum 비교 스위치 케이스 설명

public class TestClass { 
    public enum Company { 
     Google(1), 
     Microsoft(2), 
     JPMorgan(3), 
     WellsFargo(4); 

     private int companyRatings; 

     private Company(int companyValue) { 
      this.companyRatings = companyValue; 
     } 
    } 

    public static void enumComparison(Company type) { 
     switch (type) { 
      case Google: 
       System.out.println("Company Name : " + type + " - Company Position : " + type.companyRatings); 
      case Microsoft: 
       System.out.println("Company Name : " + type + " - Company Position : " + type.companyRatings); 
       break; 
      case WellsFargo: 
       System.out.println("Company Name : " + type + " - Company Position : " + type.companyRatings); 
       break; 
      default: 
       System.out.println("Company Name : " + type + " - Company Position : " + type.companyRatings); 
       break; 
     } 
    } 

    public static void main(String[] args) { 
     enumComparison(Company.Google); 
    } 
} 

그래서 당신의 참고를위한 프로그램입니다. C#에서 switch 문에는 break 키워드가 필수 항목이며, 키워드를 누락하면 컴파일 시간 오류가 발생합니다. 하지만 자바에서는 예외적 인 것으로 나타났습니다 (No Compile time error for missing the break keyword).
따라서 Main 메서드에서 나는 Company.Google을 인수로 전달합니다. break 키워드는 첫 번째 경우에서 누락되었으므로 (Case Google:) 두 번째 대소 문자 (Case Microsoft:)로 이동하고 유형 불일치가 있더라도 값을 인쇄합니다. 이상한데 왜 이런 일이 일어날 지 모르겠다. 따라서 중복 값을 인쇄합니다. 나는 혼란스러워.

출력

Company Name : Google - Company Position : 1 
Company Name : Google - Company Position : 1 
+5

이 내용을 읽어야합니다. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html –

+1

'break'또는 ' return' 또는'throw'를 실행하면 실행은 다음 케이스로 넘어갑니다. 이 기능은 Java가 C++에서 상속받은 기능으로, 동일한 방식으로 작동합니다. 여기에는 유형 불일치가 없습니다 (열거 형 상수는 모두 동일한 유형 인 '회사'). – Jesper

+0

'toString()'메소드를 오버라이드 할 수 없습니까? –

답변

1

인쇄 논리를 Company 열거 형의 toString()으로 옮기고 switch 문을 해당 유형별로 그룹화하도록 수정할 수 있습니다. 각 case이없는 switch-case을 사용하는 방법을 보여줍니다. break.

public class TestClass { 
    public enum Company { 
     Google(1), 
     Microsoft(2), 
     JPMorgan(3), 
     WellsFargo(4); 

     private int companyRatings; 

     private Company(int companyRatings) { 
      this.companyRatings = companyRatings; 
     } 

     @Override 
     public String toString() { 
      return "Company Name : " + name() + " - Company Position : " + companyRatings; 
     } 
    } 

    public static void enumComparison(Company type) { 
     switch (type) { 
      case Google: 
      case Microsoft: 
       System.out.println("[Technology Company]: " + type); 
       break; 
      case JPMorgan: 
      case WellsFargo: 
       System.out.println("[Investment Company]: " + type); 
       break; 
      default: 
       System.out.println("[General... Company]: " + type); 
       break; 
     } 
    } 

    public static void main(String[] args) { 
     enumComparison(Company.Google); 
    } 
} 
0

휴식이 필수는 아니지만, 같은 여기로 그렇게하는 것이 좋습니다 대부분의 경우는 여전히 존재한다.

P.S. : companyRatings를 private으로 설정하고 나중에 액세스하면 나중에 컴파일됩니다.

+0

컴파일 시간 오류가 전혀 표시되지 않습니다. – Aishu

+1

* companyRatings를 비공개로 설정하고 나중에 액세스하면이 컴파일이 놀랍습니다. * 여전히 동일한 클래스이므로 당연히 작동합니다. 더 많은 것 : http://stackoverflow.com/questions/1801718/why-can-outer-java-classes-access-inner-class-private-members – Tom

+0

고마워요 @ 톰! 새로운 것을 매일 새롭게 배웁니다 :-) –

0

Java에서 switch 문을 정의하는 방법입니다. 조건을 만족 한 case 문에서 break 문으로 코드가 실행됩니다. break 문이 요구되지 않는 이유

이 예제를 고려, 이해하기 :

case Google: 
    case Microsoft: 
    System.out.println("Tech Company Name : " + type + " - Company Position : " + type.companyRatings); 
    break; 
    default: 
    System.out.println("No Tech Company Name : " + type + " - Company Position : " + type.companyRatings); 
       break; 

당신은 같은 블록에 대해 여러 case 문을 가질 수 있습니다 볼 수있다.

+0

그 경우 break 문이 필수적이어야합니다. 그렇지 않으면 – Aishu

+0

과 같은 중복 출력으로 이어집니다. @Aishu는 그렇지 않습니다. 유연성이 더 뛰어납니다. – user902383

+0

예, 업데이트 된 URL을 보았습니다. 대답. 나는이 관점에서 생각하지 않았다. – Aishu

0

전혀 이상하지 않습니다. case 문에서 break을 생략하면 스마트 코드를 생성 할 수 있습니다. 여기에 작은 코드 예제입니다 :이 열거

public enum Month{ 
    January(1), 
    February(2), 
    March(3), 
    April(4), 
    May(5), 
    June(6), 
    July(7), 
    August(8), 
    September(9), 
    October(10), 
    November(11), 
    December(12); 
} 

입니다

그리고 이것은 우리가

switch (currentMonth) { 
     case January: 
      System.out.println("Months to come " + Month.February); 
     case February: 
      System.out.println("Months to come " + Month.March); 
     case March: 
      System.out.println("Months to come " + Month.April); 
     case April: 
      System.out.println("Months to come " + Month.May); 
     case May: 
      System.out.println("Months to come " + Month.June); 
     case June: 
      System.out.println("Months to come " + Month.July); 
     case July: 
      System.out.println("Months to come " + Month.August); 
     case August: 
      System.out.println("Months to come " + Month.September); 
     case September: 
      System.out.println("Months to come " + Month.October); 
     case October: 
      System.out.println("Months to come " + Month.November); 
     case November: 
      System.out.println("Months to come " + Month.December); 
     case December: 
      System.out.println("This is the last month of the year"); 
      break; 
     default: 
      System.out.println("Invalid year"); 
      break; 
    } 

당신은 확인하여 트릭을 볼 수있는 이번 달에게 전달하는 스위치 케이스 블록 출력.