代码实现:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组

import java.util.Scanner;

//输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
public class Test {

	public static void main(String[] args) {
		int[] a = genNum();
		int indexMax = getMax(a);	
		int indexMin = getMin(a);		
		swapMax(a, indexMax);		
		swapMin(a, indexMin);
		printArray(a);
	}

	public static void printArray(int[] a) {
		for (int j = 0; j < a.length; j++) {
			System.out.print(a[j] + " ");
		}
	}

	public static void swapMin(int[] a, int indexMin) {
		int temp2 = a[indexMin];
		a[indexMin] = a[a.length-1];
		a[a.length-1] = temp2;
	}

	public static void swapMax(int[] a, int indexMax) {
		int temp = a[indexMax];
		a[indexMax] = a[0];
		a[0] = temp;
	}

	public static int getMin(int[] a) {
		int min = a[0];
		int indexMin = 0 ;
		for (int j = 0; j < a.length; j++) {
			if(min>a[j]){
				min = a[j];
				indexMin= j;		
			}
		}
		return indexMin;
	}

	public static int getMax(int[] a) {
		int max = a[0];
		int indexMax = 0 ;
		for (int j = 0; j < a.length; j++) {
			if(max<a[j]){
				max = a[j];
				indexMax= j;		
			}
		}
		return indexMax;
	}

	public static int[] genNum() {
		Scanner sc = new Scanner(System.in);
		int[] a = new int[10];
		String s = "";
		int i = 0;
		System.out.println("请输入第1个整数:");
		while (true) {
			s = sc.nextLine();
			try {
				int num = Integer.parseInt(s);
				a[i] = num;
				i++;
				if (i == 10) {
					break;
				}
				System.out.println("请输入第" + (i + 1) + "个整数:");
			} catch (NumberFormatException e) {

				System.out.println("输入非法,请重新输入");
			}			
		}
		return a;
	}
}

 

posted on 2017-03-09 20:03  LoaderMan  阅读(821)  评论(0编辑  收藏  举报

导航