Java Question: Is it possible to have a switch statement within another one?
Asked Answered
S

5

8

I have a yes or no question & answer. I would like to ask another yes or no question if yes was the answer. My instructor wants us to use charAt(0) as input for the answer.

Is it possible to have a switch statement within another one (like a nested if statement)?

EDIT: Here is a sample of my pseudo code =

display "Would you like to add a link (y = yes or n = no)? "
input addLink

switch (link)
    case 'y':
        display "Would you like to pay 3 months in advance " + "(y = yes or n = no)?"
        input advancePay

                switch(advPay)
                        case 'y':
                linkCost = 0.10 * (3 * 14.95)

                case 'n'
                linkCost = 14.95            
    case 'n'
        linkCost = 0.00
Strove answered 18/10, 2009 at 1:41 Comment(4)
in the time it took you to write this question you could have tested it yourself... just saying...Bothnia
i think the point of SO is that people * n do not need to write code to test an idea.Buchner
@ande_turner : no. SO is here to answer questions, not to do things instead of people.Domingadomingo
@ValentinRocher no.Washery
B
19

Yes, but don't. If you need a further level of logic like that, place the second Switch in its own method with a descriptive name.

EDIT: By the example you've added, you've got two Boolean conditions. I would recommend against using switch at all, using if & else conditionals instead. Use (STRING.charAt(0) == 'y') as your test case, or something methodical like boolean isY(final String STRING) { return (STRING.charAt(0) == 'y' || STRING.charAt(0) == 'Y'); }

Buchner answered 18/10, 2009 at 1:44 Comment(0)
P
2

Yes. Switches break the language block statement pattern, but this is mainly because of C/C++ from which the switch statement used by Java is based.

In all three languages, the switch statement takes the following form:

switch(variable) {
     case n:
        statement 1;
        statement n;
        (optional) break;
     case n+1:
        statement 1;
        statement n;
        (optional) break;
     // Optionally more statements
     (optional) default:
        statement 1;
        statement n;
}

Because a switch statement breaks the traditional language pattern, many programmers wrap their multiple statements in a case using the traditional block style: { }

This is because most constructs in all three languages allow block style statements to be considered as one statement, but the switch statement does not require block style to execute multiple statements in a single case.

Without the break statement separating each case, there will be "fall through" - if case n was matched and did not have a break, the code under it (case n + 1) would be executed - if case n + 1 did not have a break and was matched, the default code would execute, if neither had a break, when matching case n, the code for case n, case n+1 and default would be executed.

The default is optional, and specifies a default action for a switch statement to execute. Typically, the default condition is either a generic handler, or a good place to throw an exception if the value could not logically be any other than the values in the switch statement.

To illustrate a switch statement executing inside a switch statement, take a look at this contrived example:

String message = null;
int outerVariable = getOuterVariable();
switch(outerVariable) {
     case n:
        statement 1;
        statement n;
        break;
     case n+1:
        int innerVariable = getInnerVariable();
        switch(innerVariable) {
            case 1:
                message = "IT WAS 1";
                break;
            default:
                message = "WHY WOULD YOU DO THIS?  OH THE HUMANITY!";
        }
        break;
     // Optionally more statements
     (optional) default:
        statement 1;
        statement n;
}
Paripinnate answered 18/10, 2009 at 1:56 Comment(2)
just be careful about the above code - if you are translating it into java, note that the case statements must be constant expressionsYezd
Chii - Good point. Also, Java 5's enums are allowed in switch statements as well.Paripinnate
S
1

It is possible, but that would be very convoluted and hard to read. There's almost certainly a better way, such as calling a method within the first switch statement and doing any more necessary processing (including another switch if necessary) in that method.

Shred answered 18/10, 2009 at 1:46 Comment(0)
R
0

Since Java 14+ one might want to benefit from yield capability for nesting switch expressions, e.g.:

String result =
 switch (num) {
  case 1, 2 -> "1 or 2";
  case 3 -> {
    switch (character) {
       case 'a': {
          yield "3 and a"
       }
       case 'b': {
          yield "3 and b"
       }    
    }
  }
 };
Rugen answered 5/1 at 2:20 Comment(0)
D
-1

Most programming languages are orthogonal. That means, using a feature usually does not depend on the location, if meaningful.

For example, you cannot declare a local variable as public.

Deming answered 18/10, 2009 at 1:56 Comment(1)
@Srini: I don't see how this answers the question. Specifically, it says nothing about whether switch in Java is orthogonal. Orthogonality is property that programming language designers strive for, but rarely entirely achieve. You cannot infer that any particular language construct will be orthogonal without understanding the language spec. It may be one of the exceptions.Milepost

© 2022 - 2024 — McMap. All rights reserved.