Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để thêm hai số

Trong bài này, chúng ta sẽ hiểu cách thêm hai số trong Java. Điều này có thể được thực hiện bằng cách sử dụng toán tử '+'.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

input_1 : 10
input_2 : 15

Đầu ra

Đầu ra mong muốn sẽ là -

Sum : 25

Thuật toán

Step1- Start
Step 2- Declare three integers: input_1, input_2 and sum
Step 3- Prompt the user to enter two integer value/ define the integers
Step 4- Read the values
Step 5- Add the two values using an addition operator (+)
Step 6- Display the result
Step 7- Stop

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java để thêm hai số .

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

Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.

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