题目要求:
1、输入6个数,并将它们存入数组array中;
2、最大的与第一个元素交换,最小的与最后一个元素交换,然后输出数组。
java输出数组的三种方式:
1.传统for循环
2.for each 循环 for(int a:array)? system.out.println(a);
3.Array类的toString方法
public class exchange {
public static void main(String[] args) {
int[] arr = new int[6];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
int data = sc.nextInt();
arr[i] = data;
}
System.out.println("原数组为:"+ Arrays.toString(arr));
findAndExchange(arr);
print(arr);
}
public static void findAndExchange(int[] arr1) {
int max = arr1[0];
int min = arr1[0];
int maxIndex = 0;
int minIndex = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] > max) {
max = arr1[i];
maxIndex = i;
}
if (arr1[i] < min) {
min = arr1[i];
minIndex = i;
}
}
int temp = arr1[maxIndex];
arr1[maxIndex] = arr1[0];
arr1[0] = temp;
int temp1 = arr1[minIndex];
arr1[minIndex] = arr1[arr1.length-1];
arr1[arr1.length-1] = temp1;
}
public static void print(int[] arr2){
System.out.print("交换后的数组为:[");
for (int i = 0; i < arr2.length; i++) {
if (i == arr2.length-1)
System.out.print(arr2[i]);
else {
System.out.print(arr2[i]+",");
}
}
System.out.print("]");
}
}
?python编程语言实现:python编程专栏/python11中
|