1.将一个给定的整型数组转置输出,
源数组为:1 2 3 4 5 6
转置之后输出的数组为:6 5 4 3 2 1
刚看到题目的时候没多想,只想着能倒着输出就好(正确代码错误想法)
public static void main(String[] args){
int[] a={1,2,3,4,5,6};
System.out.println("原数组为:");
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
System.out.println("倒序输出之后数组为:");
for(int i=a.length-1;i>=0;i--)
{
System.out.println(a[i]);
}
}
运行后:6 5 4 3 2 1,但是发现需要转置数组,然后又整理下思路:
思路:让数组的a[0]和a[5]交换位置,a[1]和a[4]交换位置,a[2]和a[3]交换位置,然后输出出来即可。代码如下:(错误的思路,考虑不全面)
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
int[] b = new int[6];
int i,j;
for ( i = 5; i >= 0; i--) {
for ( j = 0; j <= 5; j++) {
b[j] = a[i];
}
}
for ( j= 0; j<=5;j++){
System.out.println(b[j]);
}
}
输出结果为:1 1 1 1 1 1
接下来又重新认真想了一下错误,发现是没注意每次循环都输出六次,然后给每一个值附了六次值所造成的。然后就想到了用冒泡排序的方法进行多次比较将这个数组按从大到小的顺序排列,然后再遍历输出代码如下:
public static void main(String[] args){
int[] a={1,2,3,4,5,6};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length-1;j++){
if(a[j]<a[j+1]){
int temp=0;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
2.现在有如下的一个数组:int[] oldArr = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ;
要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为:int[] newArr = {1,3,4,5,6,6,5,4,7,6,7,5} ;
思路:通过continue语句,当oldArr[i]==0时跳出该循环将为零的项去除
public static void main(String[] args) {
int[] oldArr={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
int[] newArr=new int[oldArr.length];
int j=0;
System.out.print("oldArr:");
for(int i=0;i<oldArr.length;i++){
System.out.print(oldArr[i]);
}
for(int i=0;i<oldArr.length;i++){
if(oldArr[i]==0){
continue;//当oldArr[i]=0为零时跳出循环,并且不再执行该判断语句下面的所有语句
}
newArr[j]=oldArr[i];
j++;
}
System.out.println();
System.out.print("newArr:");
for(int m=0;m<j;m++){
//j为新数组的长度
System.out.print(newArr[m]);
}
}
输出结果:
oldArr:1345006605476705
newArr:134566547675
3.现在给出两个数组:数组a:"1,7,9,11,13,15,17,19" 数组b:"2,4,6,8,10" 现将两个数组合并为数组c。
思路:数组a,b长度之和为数组c的长度,将数组a的值赋给c之后,c中第a.length+1为b[0],此处用常量n来计数
public static void main(String[] args){
int[] a={1,3,5,7,9,11,13,15,17,19};
int[] b={2,4,6,8,10};
int m=a.length+b.length;
int[] c=new int[m];
int n=0;
System.out.print("数组a:");
for (int i = 0; i < a.length; i++){
System.out.print(a[i]+" ");
}
System.out.println();
System.out.print("数组b:");
for (int i = 0; i < b.length; i++){
System.out.print(b[i]+" ");
}
for(int i=0;i<a.length;i++){
c[i]=a[i];
n++;
}
for(int j=0;j<b.length;j++){
c[n++]=b[j];
}
System.out.println();
System.out.print("合并数组:");
for(int i=0;i<c.length;i++){
System.out.print(c[i]+" ");
}
}
输出结果:
数组a:1 3 5 7 9 11 13 15 17 19
数组b:2 4 6 8 10
合并数组:1 3 5 7 9 11 13 15 17 19 2 4 6 8 10