//定义数组存储10个数据,将数组中最大数放到第一个元素。
class Exercise09 
{
 public static void main(String[] args) 
 {
  int[] arr={1,2,3,4,5,10,6,7,8,9};//定义数组。
  PutZero pz=new PutZero();//new对象。
  pz.put(arr); 
 }
}
class PutZero
{
 int max=0;
 int temp;
 void put(int[] a)//定义方法将数组中大数和0坐标将换。
 {
  for (int i=0;i<a.length ;i++ )
  {
   if (a[i]>a[max])
   {
    int temp=i;
   }
   System.out.print(a[i]+" ");
  }
  for (int i=0;i<a.length ;i++ )//重新遍历新数组。
  {
   int t=temp;
   temp=max;
   max=t;//将数组中大数和0坐标将换。
   System.out.print(a[i]+" ");   
  }
 }
}
 
//输出结果是:
1 2 3 4 5 10 6 7 8 9 1 2 3 4 5 10 6 7 8 9
前面多1 2 3 4 5 ,后面多 6 7 8 9
帮我优化一下,谢谢

解决方案 »

  1.   

    这程序写的逻辑比较混乱,而且也没有排版:
    //定义方法将数组中大数和0坐标将换。
    void put(int[] a) {
      // 找出最大值所在位置
      for (int i=0;i<a.length ;i++ ) {
        if (a[i]>a[max]) {
          max = i; // 这句你写错了,不能重新定义变量!
        }
        System.out.print(a[i]+" ");
      }
      System.out.println("\nMax is: " + a[max]);  // 将最大值交换至 0 元素,交换这里不需要写在循环内,容易出问题
      temp = a[max];
      a[max] = a[0];
      a[0] = temp;  // 重新遍历新数组,显示数组元素
      for (int i=0;i<a.length ;i++ ) {
        System.out.print(a[i]+" ");   
      }
    }
      

  2.   

    package com.cai;//定义数组存储10个数据,将数组中最大数放到第一个元素。
    //最大元素和第一个元素互换 ,保持数组数据不变,只是顺序变化
    public class Test0 {
    public static void main(String[] args) {
    int[] arr = { 1, 2, 3, 4, 5, 10, 6, 7, 8, 9 };// 定义数组。
    PutZero pz = new PutZero();// new对象。
    pz.put(arr);
    }
    }class PutZero {
    int max = 0;
    int temp; void put(int[] a)// 定义方法将数组中大数和0坐标将换。
    {
    for (int i = 0; i < a.length; i++) {
    if (a[i] > a[max]) {
    max = i; // 这里直接用上面定义的temp就行了 }
    System.out.print(a[i] + " ");
    }
    // 需要换行
    System.out.println("----------------------");
    // 把最大的元素和第一个交换
    temp = a[0];
    a[0] = a[max];
    a[max] = temp;
    for (int i = 0; i < a.length; i++)// 重新遍历新数组。
    {
    // int t = temp;
    // temp = max;
    // max = t;// 将数组中大数和0坐标将换。
    System.out.print(a[i] + " ");
    }
    // 需要换行
    System.out.println("----------------------");
    }
    }