java - 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
解决方案
你可以做类似的事情
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]+" ");
}
}
推荐阅读
- html - 活动输入表单 - 出现标签 - 纯 css 解决方案
- ios - 设置 UITextField 的文本不会更新 UI,直到它获得焦点 | iOS
- nginx - Nginx 不监听 80 端口
- javascript - 如何使用反应挂钩订阅更改 redux?
- kubernetes-helm - 如何在 okd 环境中安装的 jenkinsx 中将 helm 从 2 升级到 3 版本
- reactjs - 如何在创建反应应用程序中使用 scss 变量?
- dart - 在飞镖中,使用第一个字符串的长度将字符串分成两部分
- c - 为什么我们在初始化链表的根时使用 node* 而不是只说 node ?
- r - 是否有可以在 R 中找到特定站点的服务器时间的编码?
- unity3d - 2D 盒子碰撞器在 Unity 中不起作用