Bài tập Java OOP: cài đặt lớp Math | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create a Math class with the following information:

In the class diagram, the underlined methods and properties are the static methods and static properties.

In the Math class:

  • PI is the static whose default value is 3.14
  • abs(x: int) is the function that returns the absolute value of x.
  • add(x: int, y: int) is the function that returns the sum of x and y.
  • subtract(x: int, y: int) is the function that returns the difference of x and y.
  • min(x: int, y: int) is the function that returns the smaller of two numbers.
  • max(x: int, y: int) is the function that returns the bigger of two numbers.
  • pow(x: int, y: int) is the function that returns the result of xy.

The program to test Math class:

class Entry {
	public static void main(String[] args) {
		System.out.println(Math.PI);
		System.out.println(Math.abs(-2));
		System.out.println(Math.add(2, 3));
		System.out.println(Math.subtract(2, 3));
		System.out.println(Math.min(2, 3));
		System.out.println(Math.max(2, 3));
		System.out.println(Math.pow(2, 3));
	}
}

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

3.14
2
5
-1
2
3
8

Instruction

Code sample:

class Math {
	public static double PI = 3.14;

	public static int abs(int x) {
		return x < 0 ? -x : x;
	}

	public static int add(int x, int y) {
		return x + y;
	}

	public static int subtract(int x, int y) {
		return x - y;
	}

	public static int min(int x, int y) {
		return x < y ? x : y;
	}

	public static int max(int x, int y) {
		return x > y ? x : y;
	}

	public static int pow(int x, int y) {
		int power = 1;
		for (int i = 0; i < y; i++) {
			power *= x;
		}
		return power;
	}
}