关于数组插入元素的问题
public class InsertNumber
{
public static void main(String[] args)
{
int arr[] = new int[100];
arr[0] = 2;
arr[1] = 4;
arr[2] = 8;
arr[3] = 5;
arr[4] = 9;
arr[5] = 11;
arr[6] = 23;
arr[7] = 22;
int temp = 8;
int j = 0;
int srt = 9;
int insert = 100;//要插入的数据
for (j = 0;j < temp ;j++ )
{
if (arr[j] == srt)
break;
for (int i = j;i < temp;i++ )
{
int demo = arr[i];
arr[i] = insert;
arr[i] = arr[i--];
temp++;
}
System.out.println(arr[j]);
}
}
}
我是想在9的位置插入100这个元素
请高手看看那里出错了
------解决方案--------------------public class InsertNumber
{
public static void main(String[] args)
{
int arr[] = new int[100];
arr[0] = 2;
arr[1] = 4;
arr[2] = 8;
arr[3] = 5;
arr[4] = 9;
arr[5] = 11;
arr[6] = 23;
arr[7] = 22;
int temp = 8;
int j = 0;
int srt = 9;
int insert = 100;//要插入的数据
for (j = 0;j < temp ;j++ )
{
if (arr[j] == srt)
break;
}
for (int i = j;i < temp;i++ )
{
int demo = arr[i];
arr[i] = insert;
arr[i] = arr[i--];
temp++;
}
System.out.println(arr[j]);
}
}
你第二个for循环在第一个for循环里面,break语句直接跳出了,当然不执行了
改了下,你看看吧
------解决方案--------------------for(int i=temp-1; i> =j; i--) arr[i+1]=arr[i];
arr[j]=insert;