I know that if-else statements are more efficient, but it is a homework that needs to be solved with a switch case. //final int myS = 'A' works, but it is entered by the scanner method and the case expressions must be constant expressions error occurs.
After a certain version of Java, it's been updated as a constant Where is it not processed as final and how should it be resolved?
import java.util.Scanner;
public class Test04 {
public static final int readData() {
Scanner sc = new Scanner(System.in);
System.out.println ("Enter: ");
return sc.nextInt();
}
public static final int myS = readData();
public static void main(String[] args) {
//final int myS = 'A';
switch (myS) {
case (myS):
case (myS + 0):
case (myS + 2):
case (myS + 3):
case (myS + 4):
case (myS + 5):
case (myS + 32 + 0):
System.out.println ("Enter Normal");
break;
default:
System.out.println ("Not Normal";
break;
}
}
}
'constant expression' refers to an expression that is evaluated at compile time.
public static final int myS = readData();
This is the problem. myS
is a variable that is determined at runtime, although the readData()
method must be executed, even though the final keyword is present. Therefore, myS
cannot be used as a case conditional expression.
© 2024 OneMinuteCode. All rights reserved.