I'm writing a dice rolling programme which has two parameters passed to the main, how many sides the dice has and the amount of times you want to throw it. I wanted to throw an exception if less than or more than two parameters are passed. How would I go about doing this?

I found this. But I'm not really sure how to use it? Surely I must somehow specify the amount of arguments that are expected before that exception can be thrown?

有帮助吗?

解决方案

Try 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.

  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top