简体   繁体   中英

I'm trying to write a simple switch statement

I know this not going to compile and run at this point. However is the switch statement right? I did get a compiler error of: class, interface, or enum expected

public class Fruit
{

  public static void main(String[] args)
  {

String choice = " ";

    switch(choice)
    {
    case " A ":  System.out.print(" Apple");
      break;

    case  " K ": System.out.println("Kiwi");
      break;

    case " P ": System.out.println("Pear");
      break;

    default: System.out.println("incorrect choice");
    }
  }
}

You are getting the error because you must be trying to use switch with String with Java version lower than 7. String support for switch statement was introduced in Java 7 and hence you need to be on the same version or higher to compile your code.

Follow this tech note to learn more about switch with String:

http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html

Strings in switch Statements

In the JDK 7 release, you can use a String object in the expression of a switch statement.

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

As mentioned, you can use a string as an expression of a case statement only with Java 7 or higher. If you can use only lower versions, then here is a work around for your code.

  1. An alphabet has a number representation. That is, CHARACTERS have fixed number codes for them - http://www.kerryr.net/pioneers/ascii2.htm

  2. You will get a String, get the first char in the string and then convert that char to its int code.

  3. Use int code instead of String choice in the old fashioned switch.

     public class Fruit { public static void main(String[] args) { String choice = ""; int code = -1; choice = "K"; code = (int) choice.charAt(0); switch (code) { case 65://A System.out.print("Apple"); break; case 75://K System.out.println("Kiwi"); break; case 80://P System.out.println("Pear"); break; default: System.out.println("incorrect choice"); } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM