How to use the Switch enclosure in Java

I am using Neatbeans 7.0 for Java programming. I wrote a switch case to select a program.

switch(menu) { case 1: { //stmt } default: { //stmt return; } } 

I get a compile time error in switch(menu)

 The Error is "strings in switch are not supported in -source 1.6 (use -source 7 or higher to enable strings in switch) 

(Alt-Enter shows the hints) "Can someone help me with this.

+4
source share
5 answers

I assume that menu is a string type, although in reality this does not match the statements of your case. Permission to use strings in switch been added in Java 7.

You can switch to Java 7 and fix the case so that it checks the string and not the integral 1 , or converts menu to an integer and checks, for example, with Integer.ParseInt() , something like:

 String menu = "1"; int menuint; try { menuint = Integer.ParseInt (menu); } catch (NumberFormatException e) { menuint = -1; } switch (menuint) { : 
+2
source

String cases in switch statements are supported in Java SE 7 , but not in previous versions of Java. You need to compile Java 7.

+4
source

The menu type is a line in the code. If you have JDK 1.6, then the expression type of the expression must be int or char.

You need to change the project properties :

  • Source: Source / Binary Format: JDK7
  • Libraries: JDK1.7
+2
source

The switch works with byte, short, char, and int primitive data types.

The string is not supported until Java-6. Java 7 supports a String object in a switch enclosure.

In Java SE 7 and later, you can use a String object in a switch statement.

More details here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

+1
source

I think it should be:

 case "1": 

....

0
source

Source: https://habr.com/ru/post/1389988/


All Articles