How to initialize static final variables based on cmd args?

Bob :

Coursework brief requires me to assign an optional cmd argument to a static final variable.

I have tried doing it in main() but compiler complains "cannot assign a value to final variable". I've tried doing it in a static method called by main() but same error. I've heard about static blocks being used in other answers but I need to be able to reach cmd args when I decide what to assign. I've also got some headaches over argument parsing as both arguments should have default values unless one is provided. Any bonus advice is very welcome.

public class FibonacciNim {
    private static Scanner myScanner = new Scanner(System.in);
    private static final int NO_OF_HEAPS;
    private static final int TOKENS_PER_HEAP;

    public static void main(String[] args) {
        // set heaps and tokens using args
        if (args.length == 0) {
            NO_OF_HEAPS = 3;
            TOKENS_PER_HEAP = 9;
        } else {
            boolean usageCorrect = false;
            for (int i = 0; i < args.length-1; i++) {
                if (args[i].equals("-heaps")) {
                    try {
                        NO_OF_HEAPS = Integer.parseInt(args[i+1]));
                        usageCorrect = true;
                    } catch (NumberFormatException e) {
                        usageCorrect = false;
                    }
                } else if (args[i].equals("-tokens")) {
                    try {
                        TOKENS_PER_HEAP = Integer.parseInt(args[i+1]);
                        usageCorrect = true;
                    } catch (NumberFormatException e) {
                        usageCorrect = false;
                    }
                }
            }
        }

        ...

    }

    ...

}

Thanks for reading!

Louis Wasserman :

You can't...actually, really assign something from the command line to a static final variable. (You might be able to by extremely dirty hackery, but this is probably not the intent of the assignment.)

What might be possible is that you're supposed to create a mutable static final and assign it to the contents of that. That's terrible practice and you really shouldn't do it in real life, but it's at least plausible. For example, you might write

static final String[] argHolder = new String[1];
public static void main(String[] args) {
  ...
  argsHolder[0] = args[0];
  ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322092&siteId=1