0

Swapping last two numbers giving ArrayIndexOutOfBoundException... Please correct me where I am doing wrong as I am new to programming and not able to find the problem... Thank you in advance...

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter the Number : ");
    int n = scan.nextInt();
    int m = n;
    int size = String.valueOf(n).length();

    int arr[] = new int[size];

    for (int i = 0; i < size; i++) {
        arr[i] = n % 10;
        n = n / 10;
    }

    System.out.println("The next permuatation will be : ");

    int temp = arr[m - 2];
    arr[m - 2] = arr[m - 1];
    arr[m - 1] = temp;

    System.out.print(arr);
}
Divyani Garg
  • 138
  • 1
  • 3
  • 15
  • 1
    This problem presents you with a great opportunity to experiment with and learn to use a debugger. If you're coding with any modern IDE, such as Eclipse or NetBeans, then you've got the tool already on your computer. Please consider running your code through this, set break points and then check the state of your variables as the code runs. – Hovercraft Full Of Eels Jul 29 '17 at 12:58
  • 1
    Or you could use a "poor-man's-debugger" -- sprinkle your program with a bunch of `System.out.println(...)` statements to see what's going on. For example, right under your `int size = ...` statement, have `System.out.println("Debug: size is: " + size);`, and do the same for other variables, especially leading up to the site of the error. – Hovercraft Full Of Eels Jul 29 '17 at 13:14
  • Of course, you would remove the println statements after you've fixed your bug. – Hovercraft Full Of Eels Jul 29 '17 at 13:14
  • Next you'll want to read [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) so that when you do get to the line that prints the array, it won't print nonsense. – Hovercraft Full Of Eels Jul 29 '17 at 13:27
  • Thanks a lot @HovercraftFullOfEels for the suggestion... This helped me lot and solved my problem... – Divyani Garg Jul 29 '17 at 13:49

0 Answers0