Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java hoán đổi hai số


Trong bài viết này, chúng ta sẽ tìm hiểu cách hoán đổi hai số trong Java. Việc này thực hiện bằng biến tạm thời.

Dưới đây là minh họa:

Đầu vào

Giả sử đầu vào:

value_1: 45, value_2: 70

Đầu ra

Kết quả mong đợi:

value_1: 70, value_2: 45

Thuật toán

Bước 1 - BẮT ĐẦU
Bước 2 - Khai báo 3 số nguyên: value_1, value_2, temp
Bước 3 - Đọc giá trị
Bước 4 - Gán value_1 cho biến tạm
Bước 5 - Gán value_2 cho value_1
Bước 6 - Gán biến tạm cho value_2
Bước 7 - Hiển thị hai giá trị
Bước 8 - 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 NumbersSwap {
    public static void main(String[] args) {
        int value_1, value_2, my_temp;
        System.out.println("The required packages have been imported");
        Scanner my_scan = new Scanner(System.in);
        System.out.println("A scanner object has been defined");
        System.out.println("Enter the first number");
        value_1 = my_scan.nextInt();
        System.out.println("Enter the second number");
        value_2 = my_scan.nextInt();
        System.out.println("----Before swap----");
        System.out.println("The first value is " + value_1 + " and the second value is " + value_2);
        my_temp = value_1;
        value_1 = value_2;
        value_2 = my_temp;
        System.out.println("----After swap----");
        System.out.println("The first value is " + value_1 + " and the second value is " + value_2);
    }
}

Đầu ra

The required packages have been imported
A scanner object has been defined
Enter the first number 112
Enter the second number 34
----Before swap----
The first value is 112 and the second value is 34
----After swap----
The first value is 34 and the second value is 112

Ví dụ 2: Giá trị định nghĩa trước

public class NumbersSwap {
    public static void main(String[] args) {
        int value_1, value_2, my_temp;
        System.out.println("The required packages have been imported");
        value_1 = 45;
        value_2 = 70;
        System.out.println("----Before swap----");
        System.out.println("The first number is " + value_1 + " and the second number is " + value_2);
        my_temp = value_1;
        value_1 = value_2;
        value_2 = my_temp;
        System.out.println("----After swap----");
        System.out.println("The first number is " + value_1 + " and the second number is " + value_2);
    }
}

Đầu ra

The required packages have been imported
----Before swap----
The first number is 45 and the second number is 70
----After swap----
The first number is 70 and the second number is 45