日期:2014-05-20 浏览次数:21089 次
//定义方法将数组中大数和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]+" ");
}
}
------解决方案--------------------
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("----------------------");
}
}