命令行参数中*的问题 [英] The issue of * in Command line argument
问题描述
我用 Java 编写了一个程序,它通过命令行参数接受输入.我从命令行输入两个数字和一个运算符.要将两个数字相乘,我必须提供输入,例如5 3 *
,但它不像写的那样工作.
I wrote a program in Java that accepts input via command line arguments.
I get an input of two numbers and an operator from the command line.
To multiply two numbers, I have to give input as e.g. 5 3 *
, but it's not working as written.
为什么不接受来自命令行的 *
?
Why is it not accepting *
from the command line?
推荐答案
那是因为 *
是一个 shell 通配符:它对 shell 有特殊的意义,它在传递给命令(在本例中为 java
).
That's because *
is a shell wildcard: it has a special meaning to the shell, which expands it before passing it on to the command (in this case, java
).
因为你需要一个文字 *
,你需要从 shell 中转义它.转义的确切方式因您的外壳而异,但您可以尝试:
Since you need a literal *
, you need to escape it from the shell. The exact way of escaping varies depending on your shell, but you can try:
java ProgramName 5 3 "*"
或者:
java ProgramName 5 3 *
<小时>
顺便说一下,如果你想知道 shell 对 *
做了什么,试着把 String[] args
的内容打印到你的 main代码>方法.您会发现它将包含目录中文件的名称.
By the way, if you want to know what the shell does with the *
, try printing the content of String[] args
to your main
method. You'll find that it will contain names of the files in your directory.
如果您需要将一些文件名作为命令行参数传递,这会很方便.
This can be handy if you need to pass some filenames as command line arguments.
例如,如果一个目录包含两个文件,a.log
和 b.log
那么命令 cat *.log
将是被shell扩展为cat a.log b.log
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
在 Bourne shell (sh
) 中,星号 (*
) 和问号 (?
) 字符是通过通配符扩展的通配符.如果没有前面的转义字符,当且仅当存在这样的文件时,*
将扩展为工作目录中所有不以句点开头的文件的名称,否则 *
保持未展开.因此,要引用字面上称为 "*"
的文件,必须告诉 shell 不要以这种方式解释它,方法是在它前面加上一个反斜杠 ().
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 ().
这篇关于命令行参数中*的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!