使用 int 代替字符串:public static void main (int[] args) [英] Using int Instead Of String: public static void main (int[] args)

查看:30
本文介绍了使用 int 代替字符串:public static void main (int[] args)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是 main 方法必须具有public static void main (String[] args){}"的形式,你不能传递 int[] 参数.

I was under the impression that the main method had to have the form "public static void main (String[] args){}", that you couldn't pass int[] arguments.

但是,在 Windows 命令行中,当运行以下 .class 文件时,它接受 int 和 string 作为参数.

However, in windows commandline, when running the following .class file, it accepted both int and string as arguments.

例如,使用此命令将给出输出stringers":java IntArgsTest stringers"

For example, using this command will give the output "stringers": "java IntArgsTest stringers"

我的问题是,为什么?为什么这段代码会接受一个字符串作为参数而不会出错?

My question is, why? Why would this code accept a string as an argument without an error?

这是我的代码.

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用来启动程序的方法,都是一个String,所有东西.它可能看起来像 int 1,但它实际上是字符串1",这是一个很大的不同.

Everything passed into main method, the one used by the JVM to start a program, is a String, everything. It may look like the int 1, but it's really the String "1", and that's a big difference.

现在有了您的代码,如果您尝试运行它会发生什么?当然它会编译得很好,因为它是有效的 Java,但是您的 main 方法签名与 JVM 要求的作为程序起点的签名不匹配.

Now with your code, what happens if you try to run it? Sure it will compile just fine since it is valid Java, but your main method signature doesn't match the one required by the JVM as the starting point of a program.

要运行您的代码,您需要添加一个有效的 main 方法,例如,

For your code to run, you'd need to add a valid main method like,

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);
   }
}

然后在程序调用的时候传入一些数字.

And then pass some numbers in when the program is called.

这篇关于使用 int 代替字符串:public static void main (int[] args)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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