在命令行上提供字符串的正确方法是什么?

时间:2018-07-02 03:39:40

标签: java

我正在创建一个程序,以查找用户给定的双精度值ArrayList的标准偏差。我要在命令行上提供一个字符串,以指示我想要平均值(均值)还是标准差(std)。但是,我很难将这些字符串提供给命令行。

这是我得到的错误:

> Exception in thread "main" java.lang.NumberFormatException: For input string: "std"
        at java.base/java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.base/java.lang.Integer.parseInt(Unknown Source)
        at java.base/java.lang.Integer.parseInt(Unknown Source)
        at StatDriver.main(StatDriver.java:28)

        public static void main(String[] args) {

          Scanner input;
          ArrayList<Double> data;
          int dataSize;
          String userInput = "";

          // Determine the appropriate array size.
          if (args.length > 0) {
             dataSize = Integer.parseInt(args[0]);
          } else {
             dataSize = 15;
          }

          // Create the array.
          data = new ArrayList<Double>(dataSize);

          // Read values from the terminal.
          input = new Scanner(System.in);
          while (input.hasNextDouble()) {
             data.add(input.nextDouble());
          }

          // Calculate and display the results.
          if(args[0] == "mean") {
              System.out.printf("Mean: %.2f\n", Stats.mean(data));
          }
          else if (args[0] == "std") {
              System.out.printf("StdDev: %.2f\n", Stats.stdDev(data));
          }
          else {
              System.out.printf("Mean: %.2f\n", Stats.mean(data));      
         }
       }
    }

1 个答案:

答案 0 :(得分:0)

This needs to be fixed:

If you are passing in a single command line argument "std" or "mean", then since args.length is greater than 0, an error will be thrown trying to parse "std" or "mean" to an Integer value.

      // Determine the appropriate array size.
      if (args.length > 0) {
         dataSize = Integer.parseInt(args[0]);
      } else {
         dataSize = 15;
      }

So if you change your check to something like this, and input "java StatDriver std 10":

The parse will succeed, as you will be able to parse the argument "10" at the second position.

  // Determine the appropriate array size.
  if (args.length > 0) {
     dataSize = Integer.parseInt(args[1]);
  } else {
     dataSize = 15;
  }

Generally if you run a program java program with command line arguments:

java MyProgram one two

public static void main(String [] args) {
    String one = args[0]; //=="one"
    String two = args[1]; //=="two"
}