0

the idea behind the code i want to write is this that i want to implement a swap function on array. in that i will be printing array elements before swap and, after swapping by calling a method

// here i mentioned the classes
import java.util.*;
class ArraySwap {

public static void main(String[] args) throws Exception {
    // digging out inputs

    Scanner scn = new Scanner(System.in);

    // taking amount of number of elements to be inserted in the array
    System.out.println("Enter number of Elements of Array : ");
    int n = scn.nextInt();
    // taking input of numbers
    System.out.println("Enter Elements of Array : ");
    int arr[] = new int[n];
    for (int i = 0; i < n; i++) {
        arr[i] = scn.nextInt();
    }
    // printing the previous array elements
    for (int i = 0; i < arr.length; i++) {
        System.out.println("The Elements in Array are : " + arr[i]);
    }
    // handling inputs
    scn.nextLine();
    System.out.println("After Swapping:");
    // calling the swap function
    getSwap(arr);
    // supposed to print the swapped array
    for (int i = 0; i < arr.length; i++) {
        System.out.println("The Elements in Array are : " + swaped[i]);
    }   
}
    
// swap function call    
public static int getSwap(int arr[]) {
    int[] swaped = Arrays.copyOf(arr, arr.length);
    int temp;
    for (int i=0; i < arr.length; i++) {
        temp = swaped[i];
        swaped[i] = swaped[i+1];
        swaped[i+1] = temp;
    }
    return swaped[i];
}
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • 1
    When `i` is `arr.length - 1`, what do you expect `swaped[i+1]` to be? – Silvio Mayolo Jul 14 '21 at 02:50
  • Also, the code should not compile because `swaped` is not defined in method `main` / class `ArraySwap`. You should return `swaped` from method `getSwap` (not just `swaped[i]` - `i` is defined only inside `for` loop) and fix the code in `main`: `int[] swaped = getSwap(arr);` – Nowhere Man Jul 14 '21 at 04:21

0 Answers0