gpt4 book ai didi

java - 到底 (args.length>0) 是什么意思?

转载 作者:行者123 更新时间:2023-12-01 06:35:24 27 4
gpt4 key购买 nike

这对你们来说可能很简单,但由于我是java新手,所以我想知道实际上什么是 接下来的部分会发生什么?

if (args.length > 0) {
file = args[0];
}


public class DomTest1 {
public static void main(String[] args) {
String file = "test1.xml";
if (args.length > 0) {
file = args[0];
}
}
}

最佳答案

这些称为命令行参数,您可以在程序中以字符串数组的形式获得它们。这是Oracle tutorial

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run.

因此下面的代码:

String file = "test1.xml";
if (args.length > 0) {
file = args[0];
}

检查 String[] args 的长度是否大于 0 ,这意味着它检查是否输入了任何命令行参数或者数组是否为空。如果输入了命令行参数,则将 file 分配给该数组的第一个元素,或者将默认的 file 分配给 test1.xml。您可以将您的类(class)运行为:

java DomTest1  someFileName.someExtension

When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the command-line arguments passed to the DomTest1 application in an array that contains a single String: "someFileName.someExtension".

关于java - 到底 (args.length>0) 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17423257/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com