我正在编写一个掷骰子程序,它有两个参数传递给主程序,骰子有多少面以及你想掷它的次数。如果传递的参数少于或多于两个,我想抛出异常。我该怎么做呢?
我找到了 this . 但是我真的不确定如何使用它?当然,我必须以某种方式指定在抛出该异常之前预期的参数数量?
最佳答案
试试这个:
public class Dice {
public static void main(String... args) {
// First, ensure there are 2 args
if (args.length != 2) {
throw new IllegalArgumentException("Exactly 2 parameters required !");
}
int firstArgInt;
int secondArgInt;
// Verify all args are integers
try {
firstArg = Integer.parseIng(args[0]);
} catch (NumberFormatException nbfe) {
// 2 possible solutions : throw an exception, or assign a default value
// - throw new IllegalArgumentException("First arg must be an integer");
// - firstArg = 42;
}
try {
secondArg = Integer.parseIng(args[1]);
} catch (NumberFormatException nbfe) {
// Same as above
}
// Etc.
}
}
关于java - 当传递给 main 的参数太多/太少时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21365222/