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.
758 Error in x, y, and format string must not be None
1235 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
776 M2 Mac fails to install rbenv install 3.1.3 due to errors
771 GDB gets version error when attempting to debug with the Presense SDK (IDE)
856 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2025 OneMinuteCode. All rights reserved.