java - 如何从命令行导入随机数量的参数?

标签 java command-line

我有一个任务要创建一个代码,该代码采用多个命令行参数并确定哪些参数高于 50,哪些低于或等于 50。该代码正在运行,但它采用的是命令行的第一个数字并将其设置为参数总数。我可以看到它采用第一个参数 [0] 并将其用作要解析的整数数量,但我不明白如何根据输入使其成为变量。

public class Distribution100

{

public static void main(String[] args)

{

    int numberOfArgs = Integer.parseInt(args[0]); // Integer n is equal to command line arguments.

int n[] = new int[numberOfArgs];

int[] array = new int[numberOfArgs]; // Establish new array and fill with integers from command line argument.

int low = 0; // Create integer low and set it to zero. This will be used later to count up based on the Command Line Argument values.

int high = 0; // create integer high and set it to zero. This will be used later to count up based on the Command Line Argument values.

for(int i = 0; i < numberOfArgs; i++) 

/*For loop to read through the array and then follow the below steps. "args.length" will run the loop based on how many arguments are entered in the command line argument. */

    {

        array[i] = Integer.parseInt(args[i]);

            if (array[i] >= 1 && array[i] <= 50) // if the number in the array falls between 1 and 50 do the next step

                {

                    low++; // Increase low integer count by 1

                }

            else if (array[i] > 50 && array[i] <= 100) // If the number in the array falls between 50 and 100 do the next step

                {

                    high++; // Increase low integer count by 1

                }

    }

    System.out.println(low + " Numbers are less than or equal to 50.");

    System.out.println(high + " Numbers are higher than 50.");

    }

}

最佳答案

命令行参数已经在数组中,只需使用它即可。

public static void main(String[] args) {
    int low = 0;
    int high = 0;
    for (String s : args) {
        try {
            int i = Integer.parseInt(s);
            if (i > 50) high++;
            else low++;
        } catch (NumberFormatException e) {
            System.err.printf("%s is not a number!\n", s);
        }
    }
    System.out.printf("%d numbers are less than or equal to 50.\n", low);
    System.out.printf("%d numbers are higher than 50.\n", high);
}

我还添加了一些内容 - 一个捕获非数字字符串的 try block ,并使用 printf 而不是 println

关于java - 如何从命令行导入随机数量的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501097/

相关文章:

bash - 使用 bash 命令行,如何将 "import package.name.*;"添加到许多 java 文件?

c - 这个字符`叫什么?

java - 从十六进制值获取各个字节

java - 一个好的 TAPI 2 Java 包装器?

ruby - 包含文件的预处理器

C++使用命令行输入txt文件但无法打开文件

GitLab CI 构建失败,无法识别 git

java - 上传aar到maven

java - 如何使用 XOM 仅在第一个标签上设置命名空间?

java - 如何使用 pdfbox 2.0.16 设置 PDAnnotationFreeText 的字体颜色