เพื่อตรวจสอบว่าเป็นไปได้หรือไม่ที่จะหารด้วย 3 ตัวเลขโดยใช้ตัวเลขทั้งหมดในอาร์เรย์ โค้ด Java มีดังต่อไปนี้ -
ตัวอย่าง
import java.io.*;
import java.util.*;
public class Demo{
public static boolean division_possible(int my_arr[], int n_val){
int rem = 0;
for (int i = 0; i < n_val; i++)
rem = (rem + my_arr[i]) % 3;
return (rem == 0);
}
public static void main(String[] args){
int my_arr[] = { 66, 90, 87, 33, 123};
int n_val = 3;
if (division_possible(my_arr, n_val))
System.out.println("It is possible to make a number that can be divided by 3");
else
System.out.println("It is not possible to make a number that can be divided by 3");
}
} ผลลัพธ์
It is possible to make a number that can be divided by 3
คลาสชื่อ Demo มีฟังก์ชันชื่อ 'divide_possible' ตรวจสอบเพื่อดูว่าสามารถใช้ตัวเลขเพื่อสร้างตัวเลขที่สามารถหารด้วย 3 ได้หรือไม่ ในฟังก์ชันหลัก อาร์เรย์ที่มีค่าและค่า 'n' ถูกกำหนดไว้ ฟังก์ชันนี้ถูกเรียกด้วยอาร์กิวเมนต์เฉพาะ และข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล