课程简介要求我为静态最终变量分配一个可选的cmd参数。
我尝试在main()中执行此操作,但是编译器抱怨“无法为最终变量赋值”。我试过在main()调用的静态方法中执行此操作,但存在相同的错误。我听说过在其他答案中使用了静态块,但是当我决定分配什么内容时,我需要能够到达cmd args。我对参数解析也有些头疼,因为除非提供一个参数,否则两个参数都应具有默认值。任何奖金建议都非常欢迎。
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;
}
}
}
}
...
}
...
}
感谢阅读!