數組元素比較大小


定義一個數組並賦值,取出最大值和最小值

import java.util.Arrays;
import java.util.Scanner;

/**
 * 
 * @ClassName: Compare
 * @Description: 定義一個數組並賦值,取出最大值和最小值
 * @author liangguiming
 * @date 2019年9月25日
 */
public class Compare {

	private int[] arr;// 定義一個數組

	/**
	 * 
	 * @Title: input
	 * @Description: 對數組進行賦值
	 * @author liangguiming
	 * @date 2019年9月25日
	 * @param
	 * @return void
	 * @throws
	 */
	public void input() {
		Scanner can = new Scanner(System.in);
		System.out.println("請確定你輸入的個數:");
		int n = can.nextInt();
		arr = new int[n];
		System.out.println("請輸入" + n + "個數:");
		for (int i = 0; i < n; i++) {
			arr[i] = can.nextInt();
		}
		can.close();
	}

	/**
	 * 
	 * @Title: compareMaxMin
	 * @Description: 用for和if語句對數組的值進行比較,取得最大值和最小值
	 * @author liangguiming
	 * @date 2019年9月25日
	 * @param
	 * @return void
	 * @throws
	 */
	public void compareMaxMin() {
		input();
		int max = arr[0];
		int min = arr[0];
		for (int j = 1; j < arr.length; j++) {
			if (max < arr[j]) {
				max = arr[j];
			}
			if (min > arr[j]) {
				min = arr[j];
			}
		}

		System.out.println("最大值:" + max);
		System.out.println("最小值:" + min);
	}

	/**
	 * 
	 * @Title: sortMaxMin
	 * @Description: 調用Arrarys函數對數組進行排序,取得最大值和最小值
	 * @author liangguiming
	 * @date 2019年9月25日
	 * @param
	 * @return void
	 * @throws
	 */
	public void sortMaxMin() {
		input();

		Arrays.sort(arr);
		System.out.println(Arrays.toString(arr));

		System.out.println("最大值:" + arr[arr.length - 1]);
		System.out.println("最小值:" + arr[0]);
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM