w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Switch structure: entering a zip code to associate it with a geographic area but only returning the first digit?

The problem is that for example if zipCode is equals to '0', its int value is actually equals to 48 and not 0.

If you do :

char c = '0';

You will see that it outputs 48. Why ?

Because in Java, the char data type is a single 16-bit Unicode character (see encoding table below).

enter image
description here

If you take a look at this table, you see that 0 is encoded as 0x0030 = 3*16^1 = 48, 1 as 0x0031 = 3*16^1 + 1*16^0 = 49.

So to avoid that :

  1. Change your case labels as case 48: case 50: case 51 (for 0,2,3) and so on
  2. Change your case labels as case '0': case '2': case '3' and so on.

Personally, I would recommend you the second solution which is actually more clear and simple.

Demo here.

If you want to keep testing on integer values in your case labels, you could do :

int zipCode = Character.getNumericValue(input.next().charAt(0));

Edit :

To get the output you want you can store the input of the user in a String variable.

    System.out.println("Enter your zip code number: ");
    String code = input.next();
    char zipCode = code.charAt(0);

        switch (zipCode) {
        case '0': case '2': case '3':
            System.out.println(code + " is on the East Coast.");
            System.out.println(code + " is an invalid ZIP Code.");

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.