Java中的String [] args有什么意义? [英] What's the point of String[] args in Java?

查看:177
本文介绍了Java中的String [] args有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当在类中声明main方法时,总是必须执行名为args的 String 数组。重点是什么?除非我生活在摇滚之中,Java中的命令行agruments几乎不再使用。当我尝试运行这个...

Whenever you declare the main method in a class, you always have to do a String array called "args". What's the point? Unless I live under a rock, command line agruments in Java are barely used anymore. And when I try and run this...

//this program won't compile
public class SomeClass {
    public static void main(){
        System.out.println("This text will never be displayed :(");
    }
}

输出以红色文字显示:


错误:在类 SomeClass 中找不到主要方法,请将主方法定义为:

     public static void main (String [] args)

Error: Main method not found in class SomeClass, please define the main method as:
    public static void main(String[] args)

我是新手Java程序员,如果有人告诉我为什么需要,我会非常感激将该参数输入主方法。

I, the newbie Java programmer, would greatly appreciate it if anyone told my why it's required to enter that parameter into a main method.

推荐答案

因为这是被调用的main方法的签名当你执行一个Java类时。需要有一些约定,哪个方法将被执行。按照惯例,它是

Because that is the signature of the main method that is called when you execute a Java class. There needs to be some convention which method will be executed. By convention it is the

public static void main(String[] args) method

是的,你确实住在岩石下,有很多使用命令行参数时的情况。为什么不使用它们?

And yes, you do live under the rock, there are plenty of situations when command line arguments are used. Why would they not be used?

你可以问:为什么需要它?为什么不选择任何其他主要方法?答案是,它会增加复杂性,带来0个好处。现在,主要功能看起来与众不同。如果你看一下,你知道它会被调用。如果要调用任何main,你必须总是问自己:主要是我正在查看要调用的那个,还是这个类中有另一个主要优先?

You could ask: why require it? Why not just pick any other main method? The answer is that it would be adding complexity with 0 benefit. As is now, main function looks distinctive. If you look at it, you know it is the one that will get called. If any main would be called, you would have to always ask yourself: is the main I am looking at the one to be invoked, or is there another main in this class which takes precedence?

这篇关于Java中的String [] args有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆