package com.heima.day13;
/* (1)模拟Arrays.toString(int[] arr);方法,自己封装一个public static String toString(int[] arr);
(2)如果int类型数组arr为null,toString方法返回字符串"null"
(3)如果int类型数组arr长度为0,toString方法返回字符串"[]"
(4)如果int类型数组arr的内容为{1,2,3,4,5},toString方法返回字符串"[1, 2, 3, 4, 5]"*/
public class Test {
public static void main(String[] args) {
int[] arr1 = null;
String s1 = toString(arr1);
System.out.println(s1);
int[] arr2 = {1,2,3,4,5};
String s2 = toString(arr2);
System.out.println(s2);
int[] arr3 = new int[0];
String s3 = toString(arr3);
System.out.println(s3);
}
public static String toString(int[] arr) {
if(arr==null)
return "null";
if(arr.length==0)
return "[]";
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < arr.length; i++) {
if(i==arr.length - 1)
sb.append(arr[i]).append("]");
else
sb.append(arr[i]).append(" ,");
}
return sb.toString();
}
}
|
|