各位JAVA高手请帮帮忙啊,我在这里万分感激

baolei724 2008-02-02 10:19:18
public class union {
public union() {
}
public static void main(String[] args) {
// TODO code application logic here
int a[]={1,3,2,5,9};
int b[]={43,54,77,98};
int a_len=a[].getLength();
int b_len=b[].getLength();
for(int i=0;i<b_len;i++)
{
if( !a.equals(b[i]) )
a[a_len++]=b[i];
}
for(int j=0;j<a_len;j++)
System.out.println("数组a,b合并后结果是:"+a[j]);
}
}
请教各位大侠,为什么这段程序编译完出现:class expected
int a_len=a[].getLength();
class expected
int b_len=b[].getLength();
...全文
168 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuanjianbin 2008-02-03
  • 打赏
  • 举报
回复
楼上的朋友们说得都很对,取得整形数组的长度是不能用getLength()方法的,要用length属性。

另外,说一下int a[] = { 1, 3, 2, 5, 9};
当你这样声明和初始化一个数组时,数组的长度是定了滴,如果执行 a[a_len++] 就会引起下标越界异常。
所以我们要重新声明一个数组。

还有if(!a.equals(b[i])) 这里equals(Object obj)方法里面是要用对象做参数的,b[i]为int,在这里也是不行的.

参考代码如下:

public class Union
{
public static void main(String[] args)
{
int a[] = { 1, 3, 2, 5, 9};
int b[] = { 43, 54, 77, 98};

int a_len = a.length;
int b_len = b.length;

int c[] = new int[a_len + b_len];

for ( int i = 0; i < a_len; i++ ) {
c[i] = a[i];
}

for ( int i = 0; i < b_len; i++ )
{
c[a_len+i] = b[i];
}
for(int j = 0; j < c.length; j++)
System.out.println("数组a,b合并后结果是:" + c[j]);
}
}
amos82 2008-02-03
  • 打赏
  • 举报
回复
不明白你的意思,程序好奇怪。
wxinb 2008-02-03
  • 打赏
  • 举报
回复
你获取数组长度的方法错了。
改正为:

(误)int a_len=a[].getLength(); ===>>> int a_len=a.length; (正)
(误)int b_len=b[].getLength(); ===>>> int b_len=b.length; (正)
hitzsf 2008-02-02
  • 打赏
  • 举报
回复
getLength()方法是String类的方法
对于数组来说 length只是一个属性 不是方法
healer_kx 2008-02-02
  • 打赏
  • 举报
回复
int   a[]={1,3,2,5,9};
int b[]={43,54,77,98};
int a_len=a[].getLength();
int b_len=b[].getLength();


这不是Java的处理方式。。。
this style;\|/

int[] a = new int[]{1,3,2,5,9};
int a_len= a.length;
favorite7w 2008-02-02
  • 打赏
  • 举报
回复
你的意图是不是要求这两个数组的并集啊?~
favorite7w 2008-02-02
  • 打赏
  • 举报
回复
你获取数组长度的方法错了,修正后的代码如下。
另外,你的代码编译正常后,运行也会出错的。因为数组越界了。


public class Union
{
public static void main(String[] args)
{
// TODO code application logic here
int a[] =
{
1, 3, 2, 5, 9};
int b[] =
{
43, 54, 77, 98};
int a_len = a.length;
int b_len = b.length;
for(int i = 0; i < b_len; i++)
{
if(!a.equals(b[i]))
a[a_len++] = b[i];
}
for(int j = 0; j < a_len; j++)
System.out.println("数组a,b合并后结果是:" + a[j]);
}
}

62,623

社区成员

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

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