Upload files to "OOP/Java/Lab/Week12"

This commit is contained in:
Aadit Agrawal 2024-10-26 02:14:29 +05:30
parent 100e80ccc3
commit 0909e7c1ae

View File

@ -0,0 +1,46 @@
public class ArrayExchange {
public static <T> 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();
}
}