[Java Basics] Question about using the final constant in the switch case statement.

Asked 1 years ago, Updated 1 years ago, 90 views

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;

        }
    }
}

java final case constant

2022-09-21 20:18

1 Answers

'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.


2022-09-21 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.