静态错误:此类没有接受 String[] 的 static void main 方法
因为我希望用户输入数字而不是我使用的字符串
public static void main(Integer[] args)
所以,为什么这是错误的?
Since I want the user to enter numbers instead of Strings I used
public static void main(Integer[] args)
So, why is this wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您的主要方法上的签名必须是:
您没有任何其他选择。如果需要,您可以通过 Integer.parseInt(someString) 将这些字符串解析为整数
The signature on your main method MUST be:
You don't have any other option. You may parse those strings as integers if you need to, via
Integer.parseInt(someString)
Main 很特殊,因为它必须存在才能启动程序,因此它需要有固定的签名。在底层,java 运行时会寻找魔术签名来启动程序。神奇的签名是
如果你想获得整数,你需要事后解析它们,使用
Main is special since it has to be present to start the program, so it's required to have a fixed signature. Under the hood, the java runtime looks for the magic signature to start the program. The magic signature is
If you want to get Integers, you'll need to parse them out after the fact, using
您的 main 方法只能有一个 String[] 数组(除非您重载它,但我们现在不讨论细节 :-D)。
但是,您可以使用 Integer.parseInt,类似
这是因为底层平台只知道如何将字符串传递给您的程序。当您打开命令提示符或终端并执行
以下操作时:
>java MyClass 3 4 5
它不知道您希望将 ["3","4","5"] 视为整数。它将处理字符串留给程序。
You can only have an array of String[] for your main method (unless you overload it, but let's not get into the details for now :-D).
However, you can change each element of the String[] args into an int by using Integer.parseInt, something like
This is because the underlying platform only knows how to pass Strings to your program. When you open up a command prompt or terminal and do:
>java MyClass 3 4 5
It doesn't know that you want ["3","4","5"] treated like integers. It leaves dealing with the Strings up to the program.
当 JVM 加载您的类并尝试执行它时,它会查找带有签名的方法 main()
任何其他内容都是不可接受的。如果您需要整数,请使用 Integer.parseInt() 方法将输入字符串转换为整数,如 Zach 提到的。我将该转换放在 try-catch 块中以捕获 NumberFormatException,并
在相应的 catch 块中添加一个转换。问候, - MS
When the JVM loads your class and tries to execute it, it looks for the method main() with the signature
Anything else is unaccptable. If you are expecting integers, use the Integer.parseInt() method to convert the input Strings to integers, as Zach mentioned. I'd put that conversion in a try-catch block to catch NumberFormatException, and have a
in the corresponding catch block. Regards, - M.S.
您需要接受一个字符串数组,并在运行时将字符串转换为整数。就按照它的工作方式...
You'll need to accept a string array, and convert the strings to integers at runtime. Just the way it works...
main 的方法签名始终是 (String[] args)。如果您要获取整数,则必须使用下面的代码片段将 args[] 转换为 int
the method signature for main is always (String[] args). If you are going to get Integers, then you have to convert the args[] to int using the snippet below