// (1)定义一个int类型的一维数组,内容为{6,2,9,15,1,5,20,7,18}
// (2)将数组最大元素与最后一位元素进行交换,最小元素与第一位元素进行交换,并打印数组
public static void main(String[] args) {
int[] arr = { 6, 2, 9, 15, 1, 5, 20, 7, 18 };
int max = arr[0];
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
max = max < arr ? arr : max;
min = min > arr ? arr : min;
}
int a=0, b=0;
for (int i = 0; i < arr.length; i++) {
if (arr == max) {
b= i;
}
if (arr == min) {
a= i;
}
}
int temp = arr[a];
arr[a] = arr[0];
arr[0] = temp;
temp = arr;
arr = arr[arr.length-1];
arr[arr.length-1] = temp;
for (int i : arr) {
System.out.print(i+" ");
}
}
突然发现代码好长作者: hjbing456 时间: 2016-5-28 23:09
可以在数组找出最值的同时用if语句去获取字符的长度值,然后进行替换作者: 何亚辉 时间: 2016-5-29 00:46
public class ClassTest {
public static void main(String[] args) {
int[] a = new int[] {6,2,9,15,1,5,20,7,18};
int[] a1 = new int[a.length];
System.arraycopy(a, 0,a1,0,a.length);
int max =a1[0]; int min = a1[8];
for (int i = 0; i < a1.length; i++) {
if (a1[i]>max){
max = a1[i];
}
if (a1[i]<min){
min = a1[i];
}
}
for (int i = 0; i < a.length; i++) {
if (a[i]==max){
a[i]=a[a.length-1];
a[a.length-1]=max;
}
if(a[i]==min){
a[i]=a[0];
a[0]=min;
}
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]+" ");
}
}
} 作者: 何亚辉 时间: 2016-5-29 00:51
package com.heima;
import java.util.Arrays;
public class ClassTest {
public static void main(String[] args) {
int[] a = new int[] {6,2,9,15,1,5,20,7,18};
int[] a1 = new int[a.length];
System.arraycopy(a, 0,a1,0,a.length);
Arrays.sort(a1);
for (int i = 0; i < a.length; i++) {
if (a[i]==a1[a.length-1]){
a[i]=a[a.length-1];
a[a.length-1]=a1[a.length-1];
}
if(a[i]==a1[0]){
a[i]=a[0];
a[0]=a1[0];
}
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]+" ");
}
}
}