从主类传递args

时间:2013-04-12 12:44:19

标签: java

我想问别人的问题,但不是我 - 因为我是初学者。 在“public JavaApplication6()”下将参数从'main'传递给变量“server”有点麻烦 简单明了的代码:

public final class JavaApplication6 {
String server;
    public static void main(String[] args) throws IOException {
    }
    public  JavaApplication6() {
        server=main(args[0]);  ??                            //here is the problem - how to pass ?
    }
}

例如,如果我在cmd下运行带有参数“java JavaApplication6 someargument”的appplication我想将字符串someargument分配给变量'server',那么它将是: server == someargument然后例如System.out.println(server)显示字符串'someargument'。

提前谢谢

4 个答案:

答案 0 :(得分:1)

您可以从命令行将参数传递给main。不在构造函数中。构造函数用于初始化类变量。

public final class JavaApplication6 {
    String server;

    //public constructor
    public  JavaApplication6(String s) {
        server=s;
    }
    //here is where the execution begins.
    public static void main(String[] args) throws IOException {
    //create a object of your class 

        JavaApplication6 app = new JavaApplication6(/*here is where you pass the arguments to the constructor*/ args[0]);


    }

}

答案 1 :(得分:0)

public final class JavaApplication6 
{
  String server;

  public static void main(String[] args) throws IOException
  {
    JavaApplication6  obj = new JavaApplication6(args[0]);//pass zeroth argument
  }

  public  JavaApplication6(String s) {
    server = s; 
    System.out.println(s); 
  }
}

运行代码时,请确保传递参数,否则会抛出异常。

答案 2 :(得分:0)

试试这个

public final class JavaApplication6 {

String server;

public  JavaApplication6(String server) {
    this.server =  server;
}

public static void main(String[] args) throws IOException {
    JavaApplication6 jv = new JavaApplication6(args[0]);
}

}

答案 3 :(得分:0)

import java.io.IOException;

public final class JavaApplication6  
{

    String server;

    public static void main(String[] args) throws IOException {
        JavaApplication6  jApp = new JavaApplication6 (args[0]);
    }

    public JavaApplication6 (String s) {
        server = s;
    }
}

运行如下程序

java JavaApplication6“localhost”