main 函数可以使用 String 而不是 String[]

Can main function take a String instead of String[]

public static void main(String[] args) 我知道通常 main 函数接受一个参数 args,它包含提供的命令行参数作为 String 对象的数组。

您问题的答案:

详情:

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html

The java command starts a Java application. It does this by starting a Java runtime environment, loading a specified class, and calling that class's main method.

The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration has the following form:

public static void main(String[] args)

如您所知,这是 main 的方法定义,您 不能 更改它。但是,您可以将 args 数组中的元素转换为任何其他 primitive 类型,考虑到它是转换为 type 赋值 运算符的左侧。

有多种方法可以实现这一点,其中之一是:

int input = Integer.valueOf(args[0]);

Why not a String or an array of Integer?

不是整数数组,因为该数组将仅涵盖可能参数的子集(您可以解析它们并获得整数,但您还需要检查它们是否为整数,否则您将获得 NumberFormatException)。

不是字符串而是字符串数组,因为最好将命令参数分开而不是将它们放在一个大字符串中,事实上,很多时候您需要单独处理命令参数。

没有可供 VM 识别为 main 方法的替代签名。只允许一个主签名,即 public static void main(String[] args)

I have not see main takes in any parameter other than String[] args. Why not a String or an array of Integer?

是的,您可以将任何 StringInteger 作为参数,但这将成为一种不同的函数 main() 方法,而不是 java 使用的方法启动你的程序。编译后,java 搜索 public static void main(String[] args){} 方法开始。如果您更改参数,那么您的程序根本不会 运行。现在使用数组将仅覆盖数组允许的特定类型的值,例如 int[] 将仅存储 int 值,类似地 String 只能有一个值,而您可能希望有多个参数.

If there is a way to specify input for the main function, please provide an example.

是的,有使用命令行(windows)和终端(linux/unix)传递参数的方法。

  1. 使用 javac Filename.java
  2. 编译您的 java 程序
  3. 运行 java 程序连同参数 java FileName param1 param2 param3 (param1、param2、param3 是您要传递的参数)。

不,您的 main 方法不能只接受一个字符串,main 方法必须使用数组语法或 varagrs 语法接受一个字符串数组,请阅读以下内容 JSL §12.1.4. Invoke Test.main

Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

public static void main(String[] args)

public static void main(String... args)

因此,您可以选择任一语法,而不仅仅是字符串。

仅供参考,您可以创建类似 public static void main(String args) 的方法,但它不会被视为 class 的 "main" 方法,JVM 将其视为起点。所以,如果你想在你的 class 中有一个 "main" 方法,那么你必须从上面的语法中选择一个。