简体   繁体   English

如何设置命令行参数存储的数组大小?

[英]How do I set the size of the array my command line arguments will be stored in?

I basically want to store my user input in an array of size 3. When I seem to put 3 in the main (String [3] args), it doesn't seem to do what I want. 我基本上想将用户输入存储在大小为3的数组中。当我似乎将3放在主字符串(字符串[3] args)中时,它似乎并没有满足我的要求。 How do I resolve this issue? 我该如何解决这个问题?

If it helps, the exercise is asking me to: Fill in the class method main of class Ex4 with code that create an array of size 3 containing strings and fills it with command line arguments. 如果有帮助,此练习将要求我:用代码创建Ex3类的类方法main,该代码创建一个包含字符串的大小为3的数组,并用命令行参数填充它。

Thanks. 谢谢。

 public class Ex4 {
 public static void main(String[] args) 
 {
 if (args.length == 1)
 {
     System.out.println(args[0]);
 }

 else if (args.length == 2 || args.length == 3)
 {
     System.out.println(args[0]);
     System.out.println(args[1]);
 }

 else 
    System.out.println("Too many arguments");
}
}

You can't control the size of the array passed to the main method. 您无法控制传递给main方法的数组的大小。 It will automatically be allocated with the size of the arguments passed to the program. 它会自动分配给传递给程序的参数大小。

You get it backwards. 你倒退了。

You define the size of that array implicitly, by the number of arguments that you pass when starting the JVM. 您可以通过启动JVM时传递的参数数量来隐式定义该数组的大小。

At runtime, within your Java code you can only check the actual length of that array. 在运行时,您只能在Java代码中检查该数组的实际长度。 For example to give an error message to the user telling him about the required number of arguments and their meaning. 例如,向用户显示错误消息,告诉用户所需的参数数量及其含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM