设计一个java函数,在数组的第i个下标钱插入一个数据元素,并保持数组元素的连续性

来源:百度知道 编辑:UC知道 时间:2024/05/19 23:46:22
我写的它有错误,请高手看看,并解释。。。。谢谢诶
package insertnumber;

public class InsertNumber {
public static void main(String args[])throws java.io.IOException{
int a[]={12,23,45,56,67,78,89,90,100};
int b[] = null;
int pos=System.in.read()-48;
int c=34;
Insert insert=new Insert();
if(insert.insertnum(a, b, pos, c)){
for(int i=0;i<a.length+1;i++)
System.out.print(b[i]);
}
}
}

package insertnumber;

public class Insert {
boolean insertnum(int []a,int []b,int pos,int c){
int i=a.length;
if(pos<0||pos>i)return false;
for(int j=0;j<pos;j++)
b[j]=a[j];
b[pos]=c;
for(int j=pos+1;j<i+1;j++){
b[j]=a[j-1];
}return true;
}
}
因为它在主类中是作为判别条件的啊

int b[] = null;
还在insertnum的方法中用到了b[pos]这肯定是错误的.

数组在建立时就是长度固定.试着运行以下代码,你就能知道自己错哪了

int[] b = null;
b[0] = 1;

我明白你的意思,b是插入后的数组,

所以你可以设置int[] b = new int[a.length+1]来代替int[] b = null;
因为很明显数组b将比数组a多一个元素.

你也可以用集合ArrayList来实现,如果你学会集合的话会发现这个用起来也挺方便的.

最后,题外话.
最好不要用System.in.read()-48的方式来接收输入的值,因为有可能会抛出
异常.
如果改成new java.util.Scanner(System.in).nextInt();会更好.

下面那个类的方法应该return一个数组 你这方法才有意义啊 你return true啥意思