java中循环是个比较重要基础,在后期,任何项目都避免不了使用循环,所以学会使用循环输出数组是非常有必要的,下面我们来看看该如何循环输出数组吧。
例1:
public class LoopArray { float[] arr; int startIndex, len; public LoopArray(int size) { arr = initArray(size); } private float[] initArray(int size) { return new float[size]; } public int getIndex() { return startIndex; } public float[] getArray() { return arr; } public int getLength() { return len; } public void put(float value) { arr[(startIndex + len) % arr.length] = value; if (len < arr.length) len++; else { startIndex = (startIndex + 1) % arr.length; } } public float[] get() { float[] data = initArray(len); for (int i = 0; i < data.length; i++) { data[i] = arr[(i + startIndex) % arr.length]; } return data; } }
例2:
/** * 对整数数组求和 */ public static long getSum(int[] nums) throws Exception { if (nums == null) { throw new Exception("错误的参数输入,不能为null!"); } long sum = 0; // 依次取得nums元素的值并累加 for (int x: nums) { sum += x; } return sum; } /** * 对整数列表求和 * * @param nums * @return * @throws Exception */ public static long getSum(List < Integer > nums) throws Exception { if (nums == null) { throw new Exception("错误的参数输入,不能为null!"); } long sum = 0; // 可以跟遍历数组一样的方式遍历列表 for (int x: nums) { sum += x; } return sum; } /** * 求多维数组的平均值 * * @param nums * @return * @throws Exception */ public static int getAvg(int[][] nums) throws Exception { if (nums == null) { throw new Exception("错误的参数输入,不能为null!"); } long sum = 0; long size = 0; // 对于二维数组,每个数组元素都是一维数组 for (int[] x: nums) { // 一维数组中的元素才是数字 for (int y: x) { sum += y; size++; } } return (int)(sum / size); }
以上就是本篇文章的所有内容,相信你已经知道该如何循环数组了,还需要了解其他java项目中常见问题及答案的话,可以来我们的网站了解具体。
推荐阅读: