여러 건 jave switch 문

그냥 사용하는 방법에 대해 많은 jave 스위치에서도 알아내려 하고 여러 사례를 발표했다. # 39 의 예를 들어, here& 뭐한테 I& # 39 m trying to do.

switch (variable)
{
    case 5..100:
        doSomething();
    break;
}

대對 할 필요가 없습니다.

switch (variable)
{
    case 5:
    case 6:
    etc.
    case 100:
        doSomething();
    break;
}

이 경우 가능한 모든 아이디어, 또는 어떤 좋은 대안은?

질문에 대한 의견 (1)
해결책

안타깝게도, it& # 39 의 자바 가상 머신 (jvm) 에 사용할 수 없습니다. # 39, ll %s/dbase/ext_table. you& 방법을 사용하여 '' 다른 경우 명령문입니다.

해설 (16)

두 번째 옵션은 fy05 좋았소 # 39 m, 왜 i& 응답자 있다고 확신할 수 없습니다. 이는 과징금의 나는한다 이 all the time):

switch (variable)
{
    case 5:
    case 6:
    etc.
    case 100:
        doSomething();
    break;
}
해설 (6)

수도 이전 문제의 답을 얻고자 할 때 아닌 신앙이니라 부는 대로 일부 대형 스위치 건 거의 없이, 그냥 합칩니다 범위 범위를 한 사건에 신청했다.


// make a switch variable so as not to change the original value
int switchVariable = variable;

//combine range 1-100 to one single case in switch
if(1 
해설 (1)

public class SwitchTest {
    public static void main(String[] args){
        for(int i = 0;i
해설 (3)

객체 지향 교체할 수 있는 옵션을 지나치게 큰 '스위치' 와 '한' a '책임' 을 사용하는 경우 / else 구문 패턴화합니다 체인 모델 의사 결정.

    • 책임 연쇄 패턴 &gt. 책임 체인에서의 패턴 &gt. 이 관계자는 분판의 있습니다. &gt. 요청에 대해 결정할 &gt. 많은 수의 핸들러도 잠재적으로 &gt. request 에 대한 작업을 할 것입니다. 이 &gt. 클래스 체인에서의 사이트용 역할 &gt. 의 요청에 채널 소스 &gt. 때까지 따라 핸들러도 목록 &gt. 처리기에서 요청을 받아 &gt. 작업 거잖나.

또한 사용하고 있는 일반 안전하다구요 입력하십시ᄃ오 구축현 예를 들어보겠습니다.

import java.util.ArrayList;
import java.util.List;

/**
* Generic enabled Object Oriented Switch/Case construct
* @param  type to switch on
*/
public class Switch
{
    private final List cases;

    public Switch()
    {
        this.cases = new ArrayList();
    }

    /**
     * Register the Cases with the Switch
     * @param c case to register
     */
    public void register(final Case c) { this.cases.add(c); }

    /**
     * Run the switch logic on some input
     * @param type input to Switch on
     */
    public void evaluate(final T type)
    {
        for (final Case c : this.cases)
        {
            if (c.of(type)) { break; }
        }
    }

    /**
     * Generic Case condition
     * @param  type to accept
     */
    public static interface Case
    {
        public boolean of(final T type);
    }

    public static abstract class AbstractCase implements Case
    {
        protected final boolean breakOnCompletion;

        protected AbstractCase()
        {
            this(true);
        }

        protected AbstractCase(final boolean breakOnCompletion)
        {
            this.breakOnCompletion = breakOnCompletion;
        }
    }

    /**
     * Example of standard "equals" case condition
     * @param  type to accept
     */
    public static abstract class EqualsCase extends AbstractCase
    {
        private final T type;

        public EqualsCase(final T type)
        {
            super();
            this.type = type;
        }

        public EqualsCase(final T type, final boolean breakOnCompletion)
        {
            super(breakOnCompletion);
            this.type = type;
        }
    }

    /**
     * Concrete example of an advanced Case conditional to match a Range of values
     * @param  type of input
     */
    public static abstract class InRangeCase extends AbstractCase
    {
        private final static int GREATER_THAN = 1;
        private final static int EQUALS = 0;
        private final static int LESS_THAN = -1;
        protected final T start;
        protected final T end;

        public InRangeCase(final T start, final T end)
        {
            this.start = start;
            this.end = end;
        }

        public InRangeCase(final T start, final T end, final boolean breakOnCompletion)
        {
            super(breakOnCompletion);
            this.start = start;
            this.end = end;
        }

        private boolean inRange(final T type)
        {
            return (type.compareTo(this.start) == EQUALS || type.compareTo(this.start) == GREATER_THAN) &&
                    (type.compareTo(this.end) == EQUALS || type.compareTo(this.end) == LESS_THAN);
        }
    }

    /**
     * Show how to apply a Chain of Responsibility Pattern to implement a Switch/Case construct
     *
     * @param args command line arguments aren't used in this example
     */
    public static void main(final String[] args)
    {
        final Switch integerSwitch = new Switch();
        final Case case1 = new EqualsCase(1)
        {
            @Override
            public boolean of(final Integer type)
            {
                if (super.type.equals(type))
                {
                    System.out.format("Case %d, break = %s\n", type, super.breakOnCompletion);
                    return super.breakOnCompletion;
                }
                else
                {
                    return false;
                }
            }
        };
        integerSwitch.register(case1);
        // more instances for each matching pattern, granted this will get verbose with lots of options but is just
        // and example of how to do standard "switch/case" logic with this pattern.
        integerSwitch.evaluate(0);
        integerSwitch.evaluate(1);
        integerSwitch.evaluate(2);

        final Switch inRangeCaseSwitch = new Switch();
        final Case rangeCase = new InRangeCase(5, 100)
        {
            @Override
            public boolean of(final Integer type)
            {
                if (super.inRange(type))
                {
                    System.out.format("Case %s is between %s and %s, break = %s\n", type, this.start, this.end, super.breakOnCompletion);
                    return super.breakOnCompletion;
                }
                else
                {
                    return false;
                }
            }
        };
        inRangeCaseSwitch.register(rangeCase);
        // run some examples
        inRangeCaseSwitch.evaluate(0);
        inRangeCaseSwitch.evaluate(10);
        inRangeCaseSwitch.evaluate(200);

        // combining both types of Case implementations
        integerSwitch.register(rangeCase);
        integerSwitch.evaluate(1);
        integerSwitch.evaluate(10);

    }
}

이는 단지 신속시작 허수아비 때리기 오류 몇 분 후면 제가 좀 더 정교한 구축상의 권능은하나님께 휩트 백업하도록 함정이거나 '명령' 에 투입될 수 있도록 패턴 '수' 의 경우 좀 더 쉽게 구현 인스턴스들도 뒤로를 호출하십시오 국제올림픽위원회 (ioc) 스타일.

이 사건에 대해서 한 번 잘 외곽진입 에로남이네 스위치 / 모두 이 캡슐화합니다 부작용은요 클래스에 대한 제표를 때는기대어 저하됨 관리할 수 있게 되는 등 it up 의 패턴 매칭 기능 및 재사용합니다 motor1.1end 더 많은 언어와 isn& # 39, 나쁜 것이 아니다.

이 업데이트는 내아기마저도 게시물로의 1 의 [사진을] 또는 향상내용 깃허브.

해설 (1)

[이 질문] [1] # 39 에 따르면, it& 완전히 폴링합니다.

그냥 동일팔레트에 똑같은 논리를 들어 있는 모든 경우에, 그 뒤에 '브레이크' 와 함께 don& # 39 동일팔레트에 없다.

switch (var) {
    case (value1):
    case (value2):
    case (value3):
        //the same logic that applies to value1, value2 and value3
        break;
    case (value4):
        //another logic
        break;
}

39 의 경우 '점프' 가 '브레이크 없이 it& 때문에' 다른 '케이스' 보살피되 '브레이크' 또는 '반환'.

편집:

답변 정말 설명, 우리가 가지고 있는 경우가 있으나 서로 다른 방식으로 똑같은 논리를 95 값이 더 적은 수의 논리, we can do.

switch (var) {
     case (96):
     case (97):
     case (98):
     case (99):
     case (100):
         //your logic, opposite to what you put in default.
         break;
     default: 
         //your logic for 1 to 95. we enter default if nothing above is met. 
         break;
}

다른 경우 더 정밀한 제어를 하는 경우, '선택' 입니다.

[1]: https://stackoverflow.com/questions/13774446/how-to-do-a-case-with-multiple-conditions # 13774469 오토메이티드

해설 (2)

기본적으로:


if (variable >= 5 && variable 
해설 (0)

// 부적합 코드 예제

switch (i) {
  case 1:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  case 3:  // Noncompliant; duplicates case 1's implementation
    doFirstThing();
    doSomething();
    break;
  default:
    doTheRest();
}

if (a >= 0 && a < 10) {
  doFirstThing();

  doTheThing();
}
else if (a >= 10 && a < 20) {
  doTheOtherThing();
}
else if (a >= 20 && a < 50) {
  doFirstThing();
  doTheThing();  // Noncompliant; duplicates first condition
}
else {
  doTheRest();
}

//Compliant 솔루션이므로

switch (i) {
  case 1:
  case 3:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  default:
    doTheRest();
}

if ((a >= 0 && a < 10) || (a >= 20 && a < 50)) {
  doFirstThing();
  doTheThing();
}
else if (a >= 10 && a < 20) {
  doTheOtherThing();
}
else {
  doTheRest();
}
해설 (2)

[바브르] [1] 라이브러리를 사용하여 이겨낼 수 있습니다

import static io.vavr.API.*;
import static io.vavr.Predicates.*;

Match(variable).of(
    Case($(isIn(5, 6, ... , 100)), () -> doSomething()),
    Case($(), () -> handleCatchAllCase())
);

이것은 물론 모든 경우에 명시적으로 나열할 디렉토리에만 이후 약간의 개선이 필요한데. 그러나 사용자 정의 조건자 쉽게 정의할 수 있다.

public static  Predicate isInRange(T lower, T upper) {
    return x -> x.compareTo(lower) >= 0 && x.compareTo(upper)  doSomething()),
    Case($(), () -> handleCatchAllCase())
);

여기에서 '대신' 는 이 같은 일이 되돌려줍니다 일치시킵니다 표현식에서는 인스턴스입니다 직접 호출 실행 가능한 방법. 경기 후 실행 가능한 수행됨 '는' 수행할 수 있다.

[공식 문서] [2] brocade. com/support/service_plans. 참조하십시오.

[1]: http://www.vavr.io &quot Vavr"; [2]: http://www.vavr.io/vavr-docs/ # _pattern_matching

해설 (0)

대체 아래와 같이 사용할 수 있습니다.


if (variable >= 5 && variable 
해설 (0)

마지막 jave 12 릴리스에는 에서 사용할 수 있는 여러 상수입니다 같은 사건으로 레이블에만 [미리봅니다 언어 기능을] (http://openjdk.java.net/jeps/12)

jdk 기능을 사용할 수 있는 표현을 릴리스에는 &gt 설정이므로 개발자 기반하는 의견을 실제 응용. 이로 인해 향후 it 가 영구적입니다 Java SE 플랫폼.

것 같습니다.

switch(variable) {
    case 1 -> doSomething();
    case 2, 3, 4 -> doSomethingElse();
};

자세한 [젶 325: 스위치 표현식에서는 (Preview)] (https://bugs.java.com/bugdatabase/view_bug.do) = jdk 8192963 bug_id?)

해설 (0)

하나의 대안으로 직접 값을 사용하는 대신 사용할 수 있는 범위 매핑이라는 switch 문은 사용하십시오.


private static final int RANGE_5_100 = 1;
private static final int RANGE_101_1000 = 2;
private static final int RANGE_1001_10000 = 3;

public boolean handleRanges(int n) {
    int rangeCode = getRangeCode(n);
    switch (rangeCode) {
        case RANGE_5_100: // doSomething();
        case RANGE_101_1000: // doSomething();
        case RANGE_1001_10000: // doSomething();
        default: // invalid range
    }
}

private int getRangeCode(int n) {
    if (n >= 5 && n = 101 && n = 1001 && n 
해설 (0)