我用 Java 编写了一个程序,它通过命令行参数接受输入。
我从命令行输入两个数字和一个运算符。
为了将两个数字相乘,我必须给出输入,例如5 3 *
,但它没有按写的那样工作。
为什么它不接受来自命令行的*
?
最佳答案
这是因为 *
是一个 shell 通配符:它对 shell 有特殊的含义,shell 在将其传递给命令之前对其进行扩展(在本例中为 java
)。
由于您需要一个文字 *
,因此您需要将其从 shell 中转义。确切的转义方式取决于您的 shell,但您可以尝试:
java ProgramName 5 3 "*"
或者:
java ProgramName 5 3 \*
<小时/>
顺便说一句,如果您想知道 shell 对 *
做了什么,请尝试将 String[] args
的内容打印到您的 main
方法。您会发现它将包含目录中文件的名称。
如果您需要传递一些文件名作为命令行参数,这会很方便。
另请参阅
-
For example, if a directory contains two files,
a.log
andb.log
then the commandcat *.log
will be expanded by the shell tocat a.log b.log
-
In Bourne shell (
sh
), the asterisk (*
) and question mark (?
) characters are wildcard characters expanded via globbing. Without a preceding escape character, an*
will expand to the names of all files in the working directory that don't start with a period if and only if there are such files, otherwise*
remains unexpanded. So to refer to a file literally called"*"
, the shell must be told not to interpret it in this way, by preceding it with a backslash (\
).
关于java - 命令行参数中 * 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718873/