簡體   English   中英

使用 int 而不是 String:public static void main (int[] args)

[英]Using int Instead Of String: public static void main (int[] args)

我的印象是 main 方法必須具有“public static void main (String[] args){}”的形式,您不能傳遞 int[] 參數。

但是,在 Windows 命令行中,當運行以下 .class 文件時,它接受 int 和 string 作為參數。

例如,使用此命令將給出輸出 "stringers": "java IntArgsTest stringers"

我的問題是,為什么? 為什么這段代碼會接受一個字符串作為參數而沒有錯誤?

這是我的代碼。

public class IntArgsTest 
{
    public static void main (int[] args)
    {

        IntArgsTest iat = new IntArgsTest(args);

    }

    public IntArgsTest(int[] n){ System.out.println(n[0]);};

}

傳遞給 main 方法的所有東西,JVM 用來啟動程序的方法,都是一個字符串,一切。 它可能看起來像 int 1,但它實際上是字符串“1”,這是一個很大的區別。

現在有了你的代碼,如果你嘗試運行它會發生什么? 當然它會編譯得很好,因為它是有效的 Java,但是您的 main 方法簽名與 JVM 要求的作為程序起點的簽名不匹配。

要運行您的代碼,您需要添加一個有效的 main 方法,例如,

public class IntArgsTest {
   public static void main(int[] args) {

      IntArgsTest iat = new IntArgsTest(args);

   }

   public IntArgsTest(int[] n) {
      System.out.println(n[0]);
   };

   public static void main(String[] args) {
      int[] intArgs = new int[args.length];

      for (int i : intArgs) {
         try {
            intArgs[i] = Integer.parseInt(args[i]);
         } catch (NumberFormatException e) {
            System.err.println("Failed trying to parse a non-numeric argument, " + args[i]);
         }
      }
      main(intArgs);
   }
}

然后在調用程序時傳入一些數字。

好吧,您可以使用任何名稱為main方法並帶有任意數量的參數。 但是 JVM 將查找具有確切簽名的main方法public static void main(String[])

您定義的main方法只是該類的另一個方法。

我現在無法訪問 Windows,但讓我稍后嘗試一下。 我確實嘗試過 Fedora,當然我得到了以下異常:

Exception in thread "main" java.lang.NoSuchMethodError: main

請注意,由於上述原因,該類可以正常編譯。

更新:我在 Windows 7 上測試過,結果是一樣的。 我很驚訝你說它對你有用。

這段代碼實際上不會運行。 當代碼編譯時(因為你不需要 main 來編譯),當你嘗試運行它時,你會得到一個"Main method not found"錯誤。

更好的是,當我運行它時,它說

 "please define the main method as: public static void main(String[] args)

此代碼包含不起作用的public static void main (int[] args) 因為 JVM 將參數值作為字符串參數。 它不需要任何 int 參數。 所以如果我們想要一個 int 參數意味着我們必須將字符串參數轉換為整數參數。 要運行此代碼,需要有效的 main 方法(例如: public static void main(String args[])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM