In the below code, during compilation, i get 'incompatible types' error. If I user other logic, like charAt(0) and all, this works fine. Isn't there any way to use string in a java switch statement? I'm using JDK 7.
Thanks.
import java.util.Scanner;
class cCode
{
public static void Main(String args [])`
{
System.out.println("Enter country code\nChoices: IND, USA, JPN, NZ, WI");
Scanner cc = new Scanner(System.in);
switch(cc)
{
case "IND":
System.out.println(cc+" refers to INDIA");
break;
case "USA":
System.out.println(cc+" refers to UNITED STATES");
break;
case "JPN":
System.out.println(cc+" refers to JAPAN");
break;
case "NZ":
System.out.println(cc+" refers to NEW ZEALAND");
break;
case "WI":
System.out.println(cc+" refers to WEST INDIES");
break;
default:
System.out.println("Invalid choice");
}
}
}
You can use below code by taking input from user.
import java.util.Scanner;
public class cCode {
public static void main(String args[]) {
System.out.println("Enter country code\nChoices: IND, USA, JPN, NZ, WI");
Scanner cc = new Scanner(System.in);
String txt = cc.nextLine();
switch (txt) {
case "IND":
System.out.println(txt + " refers to INDIA");
break;
case "USA":
System.out.println(txt + " refers to UNITED STATES");
break;
case "JPN":
System.out.println(txt + " refers to JAPAN");
break;
case "NZ":
System.out.println(txt + " refers to NEW ZEALAND");
break;
case "WI":
System.out.println(txt + " refers to WEST INDIES");
break;
default:
System.out.println("Invalid choice");
}
}}