Trong bài viết này, chúng ta sẽ tìm hiểu cách cộng hai số trong Java. Việc này thực hiện bằng toán tử '+'.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào:
input_1: 10, input_2: 15
Đầu ra
Kết quả mong đợi:
Tổng: 25
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo 3 số nguyên: input_1, input_2, sum Bước 3 - Nhập hai số từ người dùng hoặc định nghĩa trước Bước 4 - Đọc giá trị Bước 5 - Cộng hai giá trị dùng toán tử + Bước 6 - Hiển thị kết quả Bước 7 - DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.
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);
}
}
Đầu ra
A reader object has been defined Enter the first number: 23 Enter the second number: 45 The scanner object has been closed Sum of the two numbers is: 68
Ví dụ 2: Giá trị định nghĩa trước
Hai số đã được định nghĩa trước.
public class NumberAddition {
public static void main(String[] args) {
int value_1, value_2, my_sum;
value_1 = 10;
value_2 = 15;
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);
}
}
Đầu ra
The two numbers are 10 and 15 The numbers have been added using '+' operator Sum of the two numbers is: 25