【数组的操作】
题目:
现在有一个数组{2,3,5,6,7,0,7,5,4,3,0,0,0,0},要求:
将上面数组中的0去掉,将不为0的项存入一个新的数组当中,
编写程序循环遍历输出新的数组。
将数组从小到大进行排序,并遍历输出
遍历循环将数组中是7的数字改成数字8,遍历输出数组,要求使用增强for循环进行遍历
查询数组,把数组元素的值是3的下标,并输出相应的下标
package studentproject;
import java.util.Arrays;
/**
* 现在有一个数组{2,3,5,6,7,0,7,5,4,3,0,0,0,0},要求:
将上面数组中的0去掉,将不为0的项存入一个新的数组当中,
1、编写程序循环遍历输出新的数组。
2、将数组从小到大进行排序,并遍历输出
3、遍历循环将数组中是7的数字改成数字8,遍历输出数组,要求使用增强for循环进行遍历
4、查询数组,把数组元素的值是3的下标,并输出相应的下标
* @author weijiangzhu
*
*/
public class ArrayText {
public static void main(String[] args) {
int[] arr = new int[] {2,3,5,6,7,0,7,5,4,3,0,0,0,0};
//创建对象
ArrayText at = new ArrayText();
// 1、编写程序循环遍历输出新的数组。
//1.1统计非0的数有多少个
int num = at.staticsNum(arr);
//1.2创建新的数组把非0数组元素存储在新的数组中
int[] newArr = new int[num];
//新数组下标
int index = 0;
for(int i=0;i<arr.length;i++) {
if(arr[i]!=0) {
//把非0数存入新数组
newArr[index] = arr[i];
index++;
}
}
//1.3遍历输出新的数组
System.out.println("1、去0后的数组:");
at.eachArr(newArr);
// 2、将数组从小到大进行排序,并遍历输出
Arrays.sort (newArr);//用 java 环境本身提供的方法排序
System.out.println("\n2、排序后的数组:");//换行作用
at.eachArr(newArr);//遍历输出
// 3、遍历循环将数组中是7的数字改成数字8,遍历输出数组,要求使用增强for循环进行遍历
for(int i=0;i<newArr.length;i++) {
if(newArr[i]==7) {
newArr[i]=8;//赋值
}
}
//增强for循环遍历
System.out.println("\n3、修改后的数组:");
for(int ar : newArr) {
System.out.print(ar+" ");
}
// 4、查询数组,把数组元素的值是3的下标,并输出相应的下标
System.out.println("\n4、数组元素的值是3的下标有:");
for(int i=0;i<newArr.length;i++) {
if(newArr[i]==3) {
System.out.print(i+" ");
}
}
}
/**
* 统计非0的数有多少个
* @return
*/
private int staticsNum(int[] arr) {
int count=0;
for(int ar : arr) {
if(ar!=0) {
count++;
}
}
return count;
}
/**
* 遍历数组
* @param arr
* @return
*/
private void eachArr(int[] arr) {
for(int ar : arr) {
System.out.print(ar+" ");
}
}
}