[英]Passing args from main class
我想問別人一個簡單的問題,但不是我-因為我是初學者。 我在將“ main”的參數傳遞給“ public JavaApplication6()”下的變量“ 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”運行此應用程序,則想將字符串someargument分配給變量“ server”,因此它將是:server == someargument,然后例如使用System.out.println(server )顯示字符串“ someargument”。
先感謝您
您可以從命令行將參數傳遞給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]);
}
}
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);
}
}
運行代碼時,請確保傳遞參數,否則它將引發異常。
嘗試這個
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]);
}
}
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”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.