课程简介要求我为静态最终变量分配一个可选的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;
}
}
}
}
...
}
...
}
感谢阅读!
实际上,您实际上无法从命令行将某些内容分配给静态最终变量。 (您也许可以通过极度肮脏的黑客进行攻击,但这可能不是任务的目的。)
可能的情况是,您应该创建一个可变的静态final,并将其分配给它的内容。那是很糟糕的做法,您实际上不应该在现实生活中这样做,但这至少是合理的。例如,您可以编写
static final String[] argHolder = new String[1];
public static void main(String[] args) {
...
argsHolder[0] = args[0];
...
}
静态最终变量只能在初始化时分配。
public class MyClass {
private static final int NO_OF_HEAPS = 3;
}
可以在行中或在构造函数中分配非静态最终变量:
public class MyClass {
private final int NO_OF_HEAPS;
public MyClass() {
NO_OF_HEAPS = 9;
}
}
您可以;但是,通过将其更改为可变项(例如AtomicInteger
public class FibonacciNim {
private static Scanner myScanner = new Scanner(System.in);
private static final AtomicInteger NO_OF_HEAPS = new AtomicInteger(0);
private static final AtomicInteger TOKENS_PER_HEAP = new AtomicInteger(0);
public static void main(String[] args) {
// set heaps and tokens using args
if (args.length == 0) {
NO_OF_HEAPS.set(3);
TOKENS_PER_HEAP.set(3);
}
...
}
}
就解析命令行参数而言,您可以签出JCommander
http://jcommander.org/
[它提供了解析命令行参数并填充要使用的POJO的功能,因此您不必自己解析它们。