Upload files to "OOP/Java/Lab/Week12"
This commit is contained in:
parent
100e80ccc3
commit
0909e7c1ae
46
OOP/Java/Lab/Week12/ArrayExchange.java
Normal file
46
OOP/Java/Lab/Week12/ArrayExchange.java
Normal 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();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user