Để kiểm tra tất cả chữ số của số có chia hết nó, mã Java như sau:
Ví dụ
import java.io.*; public class Demo{ static boolean divisibility_check(int val, int digit){ return (digit != 0 && val % digit == 0); } static boolean divide_digits(int val){ int temp = val; while (temp > 0){ int digit = val % 10; if ((divisibility_check(val, digit)) == false) return false; temp /= 10; } return true; } public static void main(String args[]){ int val = 150; if (divide_digits(val)) System.out.println("All the digits of the number divide the number completely."); else System.out.println("All the digits of the number are not divided by the number completely."); } }
Kết quả
All the digits of the number are not divided by the number completely.
Lớp Demo chứa hàm divisibility_check, hai tham số: số và chữ số. Hàm trả về Boolean tùy kết quả true/false. Kiểm tra số khác 0 và số chia cho chữ số có chia hết không.
Hàm divide_digits Boolean nhận số làm tham số. Kiểm tra tất cả chữ số trong số có chia hết số không. Trong main, giá trị số định nghĩa, hàm gọi với giá trị này, nếu true hiển thị thông báo, ngược lại thông báo không chia hết hoàn toàn.