Search code examples
javaarraysrotationleft-to-right

Java rotation of array.


I'm very new to java please check the below code. Please tell me where am wrong

Thanks in advance

import java.io.*;

import java.util.*;

public class Solution {

public void rotate(int[] nums, int k) {
    k %= nums.length;
    reverse(nums, 0, nums.length - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, nums.length - 1);
}
 public void reverse(int[] nums, int start, int end) {
    while (start < end) {
        int temp = nums[start];
        nums[start] = nums[end];
        nums[end] = temp;
        start++;
        end--;
    }
     for(int j = 0 ; j < nums.length - 1 ; j++ )
    {
        System.out.print(nums[j] + " ");
    }

 }

}

public static void main(String[] args) {



    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    int n = in.nextInt();
    int[] nums = new int[size];


   for(int i = 0; i<nums.lenght-1;i++)
   {
       nums[i] = scan.nextInt();
   }

 rotate(nums, n);

}

}


Solution

  • OK, here is a huge list of problems with the code and following are their solutions :

    • This is a Big one..... INDENTATION : Please in the future questions provide proper indentations to your code. Without proper indentations it a pain in the ass to read lengthy codes such as your without proper context.

    • Give Comments : Comments are there in any language for a reason. They hell you to understand your choices in the code and helps us understand your thought process.

    • OK, now with the problems with the code :

    • Scope of your class Solution ends before the public static void main(String[] args) method is mentioned.

    • There is a selling mistake of the word length in your code for(int j = 0 ; j < nums.length - 1 ; j++ )

    • You have used the word in as the reference variable for the Scanner class Scanner in = new Scanner(System.in); but when taking the input inside the next for loop, you have used the word scan. Pick one.

    • The method rotate should be defined as static. You have simply used it inside your main() method without any object or class name. You cannot make a static reference to the non-static method rotate(int[], int) from the type Solution.

    Fix all this and i think your code will work just fine.