如何使程序允许在命令行上输入以空格分隔的整数列表(JAVA)

时间:2022-10-14 03:34:23

I've never worked with the command-line up until now, and have no idea how to use it. Right now I'm running an InsertionSort program on eclipse and have declared my array of integers in my driver as :

到目前为止,我从未使用过命令行,也不知道如何使用它。现在我在eclipse上运行一个InsertionSort程序,并在我的驱动程序中声明了我的整数数组:

 int arr[] = {99, 37, 17, 5, 12, 33}; 

How would I go about allowing this input on the command line instead and printing the results out that way instead? I use a MAC if that matters. Thanks.

我将如何在命令行中允许此输入,而是以这种方式打印结果?如果重要,我会使用MAC。谢谢。

1 个解决方案

#1


2  

one possible way:

一种可能的方式:

public class Numbers {
    public static void main(String[] args) {
        List<Integer> intList = new ArrayList<>();

        for (String arg : args) {
            try {
                intList.add(Integer.parseInt(arg));
            } catch (NumberFormatException e) {
                System.err.println("not an integer: " + arg);
            }
        }

        System.out.println(intList);
    }
}

then:

$ javac Numbers.java
$ java Numbers 3 6 4
[3, 6, 4]

#1


2  

one possible way:

一种可能的方式:

public class Numbers {
    public static void main(String[] args) {
        List<Integer> intList = new ArrayList<>();

        for (String arg : args) {
            try {
                intList.add(Integer.parseInt(arg));
            } catch (NumberFormatException e) {
                System.err.println("not an integer: " + arg);
            }
        }

        System.out.println(intList);
    }
}

then:

$ javac Numbers.java
$ java Numbers 3 6 4
[3, 6, 4]