我的课程作业要求我为一个静态final变量分配一个可选的cmd参数。
我已经尝试在main()中进行操作,但编译器报错“无法为最终变量赋值”。我尝试在由main()调用的静态方法中进行操作,但是出现了相同的错误。我听说过其他答案中使用静态块,但我需要在决定要分配什么时能够访问cmd参数。我还困扰于参数解析,因为两个参数都应该有默认值,除非提供了其中一个。任何额外的建议都非常受欢迎。
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;
}
}
}
}
...
}
...
}
感谢您的阅读!