取一个可选的命令行参数意味着什么



采用可选的命令行参数意味着什么?以及该段的其余部分。

当我启动时,程序会采用一个可选的命令行参数,即文件名。这个文件的内容是一个人名列表,每行一个。程序将读取这些名称并将它们存储在一个数组中。如果没有给出命令行参数,程序将只创建一个用于存储名称的空数组。

Scanner sc = new Scanner(System.in);
    Scanner input = null;
    boolean isFile = false;
    while (isFile == false){
        System.out.println("Input file name:");
        String fileName = sc.next();
        File inputFile = new File(fileName);
        if(inputFile.exists()){
            input = new Scanner(inputFile);
            isFile = true;

主方法的签名通常为public static void main(String[] args)。这里String[] args是您的命令行参数。传递给程序的所有命令行参数都将存储在args数组中。

所以,假设当您以java Sort friends.txt的形式运行"排序"程序时,这里的"friends.txt"将被称为第一个命令行参数,而args[0]的值将为friends.txt

现在假设您将"排序"程序作为java Sort运行,那么这将被称为调用程序,没有命令行参数args[0]的值将为null

强制命令行参数

如果您有以下代码,那么可以说命令行参数是强制性的,因为如果没有提供命令行参数,您不想继续。

public static void main(String[] args) throws IOException {
    if(args[0] == null){
        System.exit(0);
    }
}

可选的命令行参数

现在,考虑下面的代码。在这里,因为您正在进行代码执行,即使没有命令行参数也不会退出,或者换句话说,即使没有提供任何命令行参数,您的程序仍然可以处理/做一些事情,所以这意味着命令行参数是可选的如果您的代码不依赖于要传递的命令行参数,并且即使没有它也能正常工作,那么这意味着您的命令行自变量是可选的

public static void main(String[] args) throws IOException {
    if(args[0] != null){
        //do something with args[0]
    }
    // Do rest of the things...
}

您的案例如下:

public static void main(String[] args) throws IOException {
    ArrayList<String> personNames = new ArrayList<String>(); //It cannot be Array because size cannot be known until file is read.
    if(args[0] != null){
        //read file.
        //update personNames arraylist
        //convert to array, if it is really required
    } else{
        //this makes command line argument as optional, simply convert to array if really required and it would be of size 0.
    }
    // Do rest of the things...
}


进一步读数:

  • Java文档中的命令行参数
  • 在Java中处理命令行参数:案例已关闭

运行程序时,可以将命令行参数传递给程序。这些参数以字符串数组的形式传递到main方法中(这是main方法中的'string[]args'!)例如:

用户在调用应用程序时输入命令行参数,并在要运行的类的名称之后指定这些参数。例如,假设一个名为Sort的Java应用程序对文件中的行进行排序。要对名为friends.txt的文件中的数据进行排序,用户需要输入:

 java Sort friends.txt

这将运行"排序"应用程序,并传入字符串数组"{'friends.txt'}",其中包含一个字符串。现在,应用程序将使用此字符串作为要排序数据的文件的名称。可以按如下方式访问数据:

String fileName = args[0]; // Assuming 'args' is the name of the String array parameter

你可以在这里阅读更多关于这方面的信息。

最新更新