java.math.BigInteger.add(BigInteger val) จะ return ค่า BigInteger object ที่มีค่าเป็น ค่าเดิม บวกกับค่า val
จากตัวอย่างโค้ดข้างบน เราสร้าง BigInteger ขึ้นมาสองตัว โดยตัวแรกมีค่า 456 อีกตัวมีค่า 789 เราเอาตัวแรกมาเรียกใช้ method add แล้วก็ส่ง BigInteger ตัวที่สองไป ผลลัพธ์ที่ได้ ก็คือ 1245 ซึ่งก็คือค่า 456 + 789 นั่นเอง
import java.math.BigInteger;
public class BigIntegerExam {
 public static void main(String[] args) {
  BigInteger bi1 = new BigInteger("456");
  BigInteger bi2 = new BigInteger("789");
  System.out.println(bi1.add(bi2)); // output : 1245 (456 + 789)
  System.out.println(bi1); // output : 456
  bi1 = bi1.add(bi2);
  System.out.println(bi1); // output : 1245
  System.out.println(bi1.add(BigInteger.valueOf(1))); // output : 1246
 }
}
จากตัวอย่างโค้ดข้างบน เราสร้าง BigInteger ขึ้นมาสองตัว โดยตัวแรกมีค่า 456 อีกตัวมีค่า 789 เราเอาตัวแรกมาเรียกใช้ method add แล้วก็ส่ง BigInteger ตัวที่สองไป ผลลัพธ์ที่ได้ ก็คือ 1245 ซึ่งก็คือค่า 456 + 789 นั่นเอง
จากนั้นเราก็สั่งให้แสดงค่า BigInteger ตัวแรก ซึ่งก็จะได้ค่าของ 456 นั่นคือตัวเดิมนั่นเอง
ไม่มีความคิดเห็น :
แสดงความคิดเห็น