এই আর্টিকেলে আমরা জাভাতে দুটি নম্বর সওয়াপ (Swap) করার পদ্ধতি শিখব। এটি একটি অস্থায়ী ভেরিয়েবল (temporary variable) ব্যবহার করে করা হয়।
ডেমো
ইনপুট
মনে করুন আমাদের ইনপুট হলো -
value_1: 45, value_2: 70
আউটপুট
প্রত্যাশিত আউটপুট হবে -
value_1: 70, value_2: 45
এলগরিদম
ধাপ ১ - শুরু ধাপ ২ - তিনটি পূর্ণসংখ্যা ঘোষণা করুন: value_1, value_2 এবং temp ধাপ ৩ - মানগুলো পড়ুন ধাপ ৪ - value_1 কে অস্থায়ী ভেরিয়েবলে অ্যাসাইন করুন ধাপ ৫ - value_2 কে value_1-এ অ্যাসাইন করুন ধাপ ৬ - অস্থায়ী ভেরিয়েবল কে value_2-এ অ্যাসাইন করুন ধাপ ৭ - দুটি মান প্রদর্শন করুন ধাপ ৮ - থামুন
উদাহরণ ১
এখানে ব্যবহারকারী প্রম্পটের মাধ্যমে ইনপুট দিচ্ছেন। আপনি এটি আমাদের কোডিং গ্রাউন্ড টুলে লাইভ চেষ্টা করতে পারেন।
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 ); } } আউটপুট
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
উদাহরণ ২
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 ); } } আউটপুট
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