Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java บวกเลข 2 ตัว (Add Two Numbers)

ในบทความนี้ เราจะเรียนรู้วิธีบวกเลข 2 ตัวในภาษา Java โดยใช้ตัวดำเนินการ +

ตัวอย่างการทำงาน

อินพุต:

input_1: 10, input_2: 15

เอาต์พุต:

Sum: 25

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปร: input_1, input_2, sum
  3. รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. บวกด้วยตัวดำเนินการ +
  5. แสดงผลลัพธ์
  6. จบโปรแกรม

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;

public class NumberAddition {
    public static void main(String[] args) {
        int input_1, input_2, my_sum;

        Scanner my_scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.println("Enter the first number: ");
        input_1 = my_scanner.nextInt();
        System.out.println("Enter the second number: ");
        input_2 = my_scanner.nextInt();
        my_scanner.close();
        System.out.println("The scanner object has been closed");

        my_sum = input_1 + input_2;
        System.out.println("Sum of the two numbers is: ");
        System.out.println(my_sum);
    }
}

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class NumberAddition {
    public static void main(String[] args) {
        int value_1 = 10, value_2 = 15, my_sum;

        System.out.printf("The two numbers are %d and %d", value_1, value_2);
        System.out.printf("\n");
        my_sum = value_1 + value_2;
        System.out.println("The numbers have been added using '+' operator");
        System.out.println("\nSum of the two numbers is: ");
        System.out.println(my_sum);
    }
}

ขยายความ: บวกหลายตัวเลข

// ใช้ลูป
int sum = 0;
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
    sum += num;
}

// ใช้ Stream (Java 8+)
int sum = Arrays.stream(numbers).sum();

การบวกเป็นพื้นฐานสำคัญของการเขียนโปรแกรม ใช้ได้กับทุกชนิดข้อมูลตัวเลข (int, long, float, double)