Concepts / Switch Statements with Numeric Values

Switch Statements with Numeric Values

A switch statement can branch on a String value, letting the program react to a unit name typed by the user.

  • Programming

Why Lengths Must Share One Unit

Suppose a program asks a user for a length and needs every length in the same unit before it can do any calculation. A user might type a distance in feet, another in yards, and another in miles. The program cannot simply add those numbers together, because a value of 3 in feet and a value of 3 in yards describe very different distances. The program must first translate each measurement into one standard unit. In this article, that standard unit is the inch.

What do you think happens?

Without calculating anything, do you think 3 feet and 3 yards describe the same distance?

  • Yes, the same number means the same length

  • No, a yard is longer than a foot

Reveal answer
Answer:

No. 3 feet is 36 inches and 3 yards is 108 inches, so the two lengths are different.

Each foot is 12 inches and each yard is 36 inches. The same number multiplied by different conversion factors gives different results, which is why the program must convert before it combines measurements.

Two Ways to Ask for a Unit

There is more than one way to ask the user for a unit. One design gives the user a menu of numbered options and reads a choice number. A second design asks the user to type the unit's name, such as inch or feet, and then uses that text directly to decide what to do. The second design is the focus here, because it shows how a switch statement can work with strings rather than only with numbers.

Following One Input Through the Switch

Before reading the rules, follow the program's path for a single input. Watch which lines run when the user types a unit name, which branch of the switch is selected, and what value is stored in the variable for inches. Notice where the path changes when the unit name changes. Your goal is to be able to say, at each step, what the program is doing and what it has stored so far.

A switch statement checks the value of a variable and chooses one case to run. In the string version, the variable holds text rather than a number. The variable named units holds whatever unit name the user typed, and the switch compares that text against the labels in each case. The program runs the first case whose label matches, and skips the rest.

units = yardstext typed by the userIs units inch,inches, or in?first case checkedIs units feet?second case checkedIs units yards?match foundinches = value times36yards conversion runsLeave the switchbreak ends the caseUse inches valuenext step after the switchcomparenonoyesthencontinue
When the user types yards, which case is reached, which statements run, and where does execution go next? The program checks each label in order, skips the non-matching cases, runs the yards conversion, and then leaves the switch.
Worked example

Tracing the Input yards

The user types yards and then enters the value 3. Trace the switch and state the value stored in inches.

  1. 1
    Read the unit

    The variable units now holds the text yards.

  2. 2
    Check the inch labels

    The text yards matches none of inch, inches, or in, so that case is skipped.

  3. 3
    Check the feet label

    The text yards does not match feet, so that case is also skipped.

  4. 4
    Reach the yards case

    The text matches the yards label, so the program runs the statements in this case and skips the rest.

  5. 5
    Apply the factor

    One yard is 36 inches, so 3 yards is 3 times 36, which stores 108 in inches.

Result

The yards branch runs and inches holds 108.

Matching Several Spellings in One Case

A single case can list several labels separated by commas. This is useful because one unit usually has a full name, a plural form, and an abbreviation. For inches, the source accepts the labels inch, inches, and in, and all three lead to the same action. Writing the labels together keeps the three spellings in one place, so the same action is not repeated three times.

switch (units)the variable holding thetyped textcase "inch":first spelling of inchescase "inches":plural spelling of inchescase "in":abbreviation, same actioninches = value;shared action for all threebreak;leaves the switch
How does the String the user types get compared against each case label to choose a branch? Each label is a separate match point, and all of them lead to the same statement.
java
Output
3.0 yards = 108.0 inches
Notes on the code
  • units holds the text typed by the user, and the switch compares it with each case label.
  • The three inch labels share one body, so all three spellings produce the same action.
  • The break statement ends the case so that the remaining cases are not run.
  • The default case runs only when no label matches.

Conversion Factors for Each Unit

Each unit other than the inch needs a conversion factor, which is the number of inches in one of that unit. The source uses three of them. One foot is 12 inches, so a measurement in feet is multiplied by 12. One yard is 36 inches, so a measurement in yards is multiplied by 36. A mile is 5280 feet and each foot is 12 inches, so the factor for miles is 12 times 5280, which is 63360 inches per mile.

inchfactor 1feetfactor 12yardsfactor 36milesfactor 12 times 5280, whichis 63360
Which multiplier applies to each unit, and how does each input unit map to its conversion factor to produce inches? Each unit name is a key, and its factor is the value used to produce inches.
Rule

Tracing an Unrecognized Unit

The switch has a default case, which runs when no other label matches. The source uses it to catch any unit name the program does not recognize. Typing a unit such as furlong, or misspelling feet as fete, matches no label, so the default branch runs. That branch prints a message saying the unit is illegal and then ends the program.

Trace the path for the input fete. The program checks the inch labels, then the feet label, then the yards and miles labels. None matches, so control reaches the default case. The default case reports the illegal unit and stops the program, so no conversion step runs and the variable for inches is never given a converted value. Stopping is the right behavior here, because a result computed from an unknown unit would be meaningless.

Debugging

A user enters Feet with a capital F. The text Feet is not the same as the label feet, so no case matches, the default branch prints the illegal unit message, and the program ends. Tracing the path reveals that the problem is the case of the letters, not the switch itself.

Mistakes That Stop a Trace

Most errors with this kind of program come from the text the user types not matching the labels exactly. Each mistake below shows where a trace would reveal the problem.

  • Common mistake

    Expecting a misspelled unit to be corrected automatically

    What it looks like

    The user types fete instead of feet.

    Why it fails

    Each label must match the typed text. A misspelling matches no label.

    Do this instead

    Trace the input: no case matches, the default case runs, and the program reports an illegal unit.

  • Common mistake

    Assuming the miles factor is 5280

    What it looks like

    Using inches = value * 5280 for a value in miles.

    Why it fails

    5280 converts miles to feet, not to inches.

    Do this instead

    Use 12 * 5280, which is 63360 inches per mile.

  • Common mistake

    Forgetting that the three inch labels share one action

    What it looks like

    Writing the inch body three separate times for inch, inches, and in.

    Why it fails

    The labels are listed together so one action serves all three spellings.

    Do this instead

    List the labels together above a single body ending in break.

  • Common mistake

    Treating the switch as if it compares numbers only, when the string version compares text

Predicting Results for New Inputs

MEDIUM

Without running the program, trace each input below through the switch. For each one, name the branch that runs and write the value stored in inches, or state that the default branch runs. Inputs: (a) 2 and feet, (b) 5 and miles, (c) 4 and in, (d) 1 and furlong.

Hints
  • Check the labels in the order they appear in the switch and stop at the first match.
  • Use the factor 12 for feet, 12 times 5280 for miles, and 1 for inch labels.
  • A unit that matches no label runs the default case and the program ends.

Key Takeaways

  • A switch statement with a String variable compares the typed unit name against each case label and runs the first case that matches.
  • One case can list several labels, such as inch, inches, and in, so that several spellings share one action.
  • Each unit converts to inches with a factor: 1 for inch, 12 for feet, 36 for yards, and 12 times 5280, which is 63360, for miles.
  • A unit that matches no label runs the default case, which reports an illegal unit and ends the program before any conversion.