- 设计一个方法用于遍历数组,要求遍历的结果是在一行上的。例如:[11,22,33,44,55]
public class index {public static void main(String[] args) {int[] arr = {11,22,33,44,55};printArr(arr);}public static void printArr(int[] arr){System.out.print("[");for (int i = 0; i < arr.length; i++) {if(i == arr.length - 1){System.out.print(arr[i]);}else{System.out.print(arr[i] + ", ");}}System.out.print("]");}
}
public class index {public static void main(String[] args) {int[] arr = {11,22,33,44,55};int max = getMax(arr);System.out.println(max);}public static int getMax(int[] arr){int max = arr[0];for (int i = 1; i < arr.length; i++) {if(arr[i] > max){max = arr[i];}}return max;}
}
- 定义一个方法判断数组中的某个数是否存在,将结果返回给调用处
public class index {public static void main(String[] args) {int[] arr = {11,22,33,44,55};boolean flag = contains(arr, 22);System.out.println(flag);}public static boolean contains(int[] arr,int number){for (int i = 0; i < arr.length; i++) {if(arr[i] == number){return true;}}//只有在数组里面全部数据都比较完毕后,才能判断该数不在数组里面//return:如果方法执行到了return,那么整个方法全部结束,里面的循环也结束return false;}
}
- 定义一个方法copyOfRange(int[] arr,int from,int to),将数组arr从索引from(包含from)到索引to(不包含to)的元素复制到新数组中并返回
public class index {public static void main(String[] args) {int[] arr = {1,2,3,4,5,6,7,8,9};int[] copyArr = copyOfRange(arr, 3, 7);for (int i = 0; i < copyArr.length; i++) {System.out.print(copyArr[i] + " ");}}public static int[] copyOfRange(int[] arr,int from,int to){//定义新数组int[] newArr = new int[to - from];int index = 0;for (int i = from; i < to; i++) {newArr[index] = arr[i];index++;}return newArr;}
}