String字符串分割成到int[]里,高手来下

zzxx8880 2010-03-17 10:04:31
有字符串String str = "1,2,3,4";

效果是int[] a ={1,2,3,4};

String str = "1,2,3,4";

String[] b = str.split(",");
int[] a = null;
for(int i=0;i<b.length;i++){
a[i] = Integer.parseInt(b[i]);
System.out.println(a[i]);
}

报错 数组a空指针,
数组a要怎么定义才行,高手指点下
...全文
219 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
aSysBang 2010-03-18
  • 打赏
  • 举报
回复
new 下就可以了
不过建议用split 函数 用不着自己写
xxpp688 2010-03-18
  • 打赏
  • 举报
回复
int []a=null ;//不能像C# 那样初始化
int []a = new int [4];//正常初始化把int[]a放进堆中(进内存),从而可以调用
老张吃嫩草 2010-03-18
  • 打赏
  • 举报
回复
顶10楼!!!
beanj 2010-03-18
  • 打赏
  • 举报
回复

String str = "1,2,3,4";
String[] b = str.split(",");
int[] a = new int[b.length];
for(int i=0;i<b.length;i++){
a[i] = Integer.parseInt(b[i]);
System.out.println(a[i]);

lhlove271015 2010-03-18
  • 打赏
  • 举报
回复
String str = "1,2,3,4";
String[] b = str.split(",");
int[] a = new int[b.length];
for(int i=0;i<b.length;i++){
a[i] = Integer.parseInt(b[i]);
System.out.println(a[i]);
}

绝对正确
aa870816 2010-03-18
  • 打赏
  • 举报
回复
顶1楼
keeya0416 2010-03-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 chen09 的回复:]
int[] a = new int[b.length];
[/Quote]
正解
hardycheng 2010-03-18
  • 打赏
  • 举报
回复
int[] a = null; 不能这样啊老兄!

这个就像口头承诺一样,没有签字啥的,到时候用的时候不能当做合同来用的,所以就空指针异常了!
像这种长度不定的数组,最好用list或者map之类的COLLECTION 来实现最好不过了。
soton_dolphin 2010-03-18
  • 打赏
  • 举报
回复
你只是声明了一个数组a,但是还没有在内存上创建

int[] a = new int[4];
txg6640530 2010-03-18
  • 打赏
  • 举报
回复
二楼正解
Arthur0088 2010-03-17
  • 打赏
  • 举报
回复
int a[] = null; // 还没有分配内存空间,必须使用new之后才有空间
zzxx8880 2010-03-17
  • 打赏
  • 举报
回复
谢谢大家的回答
BigKing911 2010-03-17
  • 打赏
  • 举报
回复
楼主的意思大概是不晓得字符串的长度,所以不 好给数组覆初值。
个人觉得有俩个比较好的解决方案:
1,是按二楼的。
2,是用list来装。
junmasky 2010-03-17
  • 打赏
  • 举报
回复
数组没有初始化,应该为:

String str = "1,2,3,4";

String[] b = str.split(",");
int[] a = new int[4];
for(int i=0;i<b.length;i++){
a[i] = Integer.parseInt(b[i]);
System.out.println(a[i]);
chen09 2010-03-17
  • 打赏
  • 举报
回复
int[] a = new int[b.length];

62,624

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧