繁体   English   中英

在运行时声明数组的大小

[英]Declare size of an array at Runtime

我正在编写一个程序,将所有文件的内容复制到最后一个输入文件中(所有文件都由用户在命令提示符下给出)。 那么,我如何声明一个从用户那里获取大小的数组?

这样做:

import java.util.Scanner;  <-------- import the class

public class InputFromUser { 

    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);    
        System.out.println("Enter a number for the array size:");
        int size = scan.nextInt();    
        int[] arr = new int[size];

    }

}

要么像这样使用java.io

BufferedReader columnInput = new BufferedReader(new InputStreamReader (System.in));
int size = Integer.parseInt(columnInput.readLine());

如果在运行应用程序时提供的文件列表作为参数:您可以使用 args.length 属性返回所提供参数的数量:

public static void main(String[] args) {
        System.out.println(args.length);
}

你也可以这样做:

public static void main(String args[]) {
    BufferedReader input = new BufferedReader (new InputStreamReader(System.in));
    try {
      System.out.println("Enter a array size:");
      int arraysize = Integer.parseInt(input.readLine());
      int[] arr = new int[arraysize];

    } catch (Exception e) {
      e.printStackTrace();
    }
}

暂无
暂无

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

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