首页 > 解决方案 > How to take 2D array inputs from command Line arguments in java?

问题描述

I have to take inputs from the command line and assign them to a 2X2 array.

Input = 1 2 3 4 (from cmd line)
output = 1 2 
         3 4


  int a[][] = new int[2][2];
        // taking 2D array inputof size 2X2 from cmdline
        for(int i=0;i<a.length;i++){
            for(int j=0;j<a[i].length;j++){
                int n = Integer.parseInt(args[i]);
                a[i][j] = n;
          }
        }
        for(int i=0;i<args.length;i++){
            for(int j=0;j<a[0].length;j++){
                System.out.print(a[i][j]+" ");
          }
       }

But Getting output as:

1 1 
2 2 

标签: javaarrays

解决方案


你可以做类似的事情

public static void main(String[] args)
{
    int a[][] = new int[2][2];

    for(int i=0; i<2; ++i)
    {
        for(int j=0; j<2; ++j)
        {
            a[i][j]=Integer.parseInt(args[2*i+j]);
        }
    }
}

命令行参数将存储在数组中的位置args。使用 将字符串转换为数字parseInt()

2*i+j用于获取args数组的适当索引。

还应为此添加适当的异常处理。

打印结果如

for(int i=0; i<2; ++i)
{
     for(int j=0; j<2; ++j)
     { 
          System.out.println(a[i][j]+" ");
     }
}

推荐阅读