From 0909e7c1ae57508f720d1bead456e862f8fb0d98 Mon Sep 17 00:00:00 2001 From: Aadit Agrawal Date: Sat, 26 Oct 2024 02:14:29 +0530 Subject: [PATCH] Upload files to "OOP/Java/Lab/Week12" --- OOP/Java/Lab/Week12/ArrayExchange.java | 46 ++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 OOP/Java/Lab/Week12/ArrayExchange.java diff --git a/OOP/Java/Lab/Week12/ArrayExchange.java b/OOP/Java/Lab/Week12/ArrayExchange.java new file mode 100644 index 0000000..5d9c518 --- /dev/null +++ b/OOP/Java/Lab/Week12/ArrayExchange.java @@ -0,0 +1,46 @@ +public class ArrayExchange { + + public static void swapElements(T[] array, int pos1, int pos2) { + T temp = array[pos1]; + array[pos1] = array[pos2]; + array[pos2] = temp; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter number of elements: "); + int size = scanner.nextInt(); + scanner.nextLine(); // consume newline + + String[] array = new String[size]; + + // Get array elements from user + for (int i = 0; i < size; i++) { + System.out.print("Enter element " + i + ": "); + array[i] = scanner.nextLine(); + } + + System.out.println("\nOriginal array: "); + for (String element : array) { + System.out.print(element + " "); + } + + System.out.print("\nEnter first position to swap: "); + int pos1 = scanner.nextInt(); + + System.out.print("Enter second position to swap: "); + int pos2 = scanner.nextInt(); + + swapElements(array, pos1, pos2); + + System.out.println( + "\nArray after swapping positions " + pos1 + " and " + pos2 + ": " + ); + for (String element : array) { + System.out.print(element + " "); + } + + scanner.close(); + } +}