การใช้ compareTo(BigInteger val) ใน BigInteger
การใช้ compareTo(BigInteger val) ใน BigInteger
บทความนี้เรามาดูวิธีการใช้ และรายละเอียดเกี่ยวกับ method ที่ชื่อว่า compareTo(BigInteger val) ซึ่งเป็น method ของ BigInteger ในภาษา Java กันครับmethod compareTo(BigInteger val) เป็น method สำหรับการเปรียบเทียบ
เรามาดูตัวอย่างโค้ดกันครับ
import java.math.BigInteger; public class BigIntegerExam { public static void main(String[] args) { BigInteger bi1 = new BigInteger("7"); BigInteger bi2 = new BigInteger("4"); // create int object int res; // compare bi1 with bi2 res = bi1.compareTo(bi2); if (res == 0) { System.out.println("Both values are equal"); } else if (res == 1) { System.out.println("First Value is greater"); } else if (res == -1) { System.out.println("Second value is greater"); } } }จากโค้ดข้างบนจะได้ผลลัพธ์คือ
First Value is greater
จากตัวอย่างโค้ดข้างบนจะเห็นว่า เราสามารถเปรียบเทียบค่าใน BigInteger ได้ โดยใช้ compareTo ถ้าเท่ากันจะ return ออกมาเป็น 0 ถ้าตัวแรกมากกว่าจะ return 1 แต่ถ้าน้อยกว่าจะ return -1
ที่มา http://www.functionexam.com/Java/java.math/BigInteger/compareTo(BigInteger-val).htm