Bài tập Java OOP: nạp chồng phương thức | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create an ArrayCalculator class in the file ArrayCalculator.java with the following information:

Explanation:

  • ArrayCalculator is a class without attributes.
  • maxOfArray(arr: int[]) and maxOfArray(arr: double[]) are two overridden static methods, they return the largest value in array arr.
  • minOfArray(arr: int[]) and minOfArray(arr: double[]) are two overridden static methods, they return the smallest value in array arr.

A program to test the above ArrayCalculator class: 

class Entry {
	public static void main(String[] args) {
		int[] arr1 = new int[] { 3, 4, 2 };
		double[] arr2 = new double[] { 1.3, 4.2, 6.7 };
		
		System.out.println(ArrayCalculator.minOfArray(arr1));
		System.out.println(ArrayCalculator.minOfArray(arr2));
		System.out.println(ArrayCalculator.maxOfArray(arr1));
		System.out.println(ArrayCalculator.maxOfArray(arr2));
	}
}

When the above code is compiled and executed, it produces the following result:

2
1.3
4
6.7

Instruction

Code sample:

public class ArrayCalculator {
	public static int maxOfArray(int arr[]) {
		int maxValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (arr[i] > maxValue) {
				maxValue = arr[i];
			}
		}
		return maxValue;
	}

	public static double maxOfArray(double arr[]) {
		double maxValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (arr[i] > maxValue) {
				maxValue = arr[i];
			}
		}
		return maxValue;
	}

	public static int minOfArray(int arr[]) {
		int minValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (arr[i] < minValue) {
				minValue = arr[i];
			}
		}
		return minValue;
	}

	public static double minOfArray(double arr[]) {
		double minValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (arr[i] < minValue) {
				minValue = arr[i];
			}
		}
		return minValue;
	}
}
​