本帖最后由 贾联国 于 2012-4-30 01:50 编辑
第二种方法不是for(int i = 0; i < iMax; i++),而是for(int i = 0; i <= iMax; i++)
先运行- class ToDemo
- {
- public static void main(String[] args)
- {
- int arr []=new int[]{1,2,3,4,5,6};
- System.out.println(myToString(arr));
- }
- public static String myToString(int[] a)
- {
- int iMax = a.length - 1;
- if (iMax == -1)
- return "[]";
- else{StringBuilder b = new StringBuilder();
- b.append('[');
- for (int i = 0; ; i++,System.out.println(i)) {
- b.append(a);
- if (i == iMax)
- return b.append(']').toString();
- b.append(", ");
- }
- }
- }
- }
复制代码 再运行以下程序
- <P>class ToDemo
- {
- public static void main(String[] args)
- {
- int arr []=new int[]{1,2,3,4,5,6};
-
- System.out.println(myToString(arr));
- }
- public static String myToString(int[] a)
- {
- int iMax = a.length - 1;
- if (iMax == -1)
- return "[]";
- else{StringBuilder b = new StringBuilder();
- b.append('[');
- for (int i = 0; i <= iMax; i++, System.out.println(i))
- {
- b.append(a);
- b.append(", ");
- }
- return b.append(']').toString();
- }
- }
- }
- </P>
复制代码 |