我有一个任务要创建一个代码,该代码采用多个命令行参数并确定哪些参数高于 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/