suresh
suresh

Reputation: 177

How to increment instance variable from method

Here is my code

public class AlphaSwap {

    public static void main(String[] args) {
        String input[] = { "a", "b", "c", "_" };
        int start = 0;
        int end = input.length - 1;

        AlphaSwap alphaSwap = new AlphaSwap();
        alphaSwap.swapFirst(input, start, end);

        //swapLast(input, start, end);

        for (String string : input) {
            System.out.println(string);
        }
        System.out.println(start);
        System.out.println(end);
    }

    private void swapFirst(String[] input, int i, int j) {
        String temp = input[i];
        input[i] = input[j];
        input[j] = temp;
        i++;
    }
}

I will have some more method to do set of operation. Here I want to increment the value of start variable from swapFirst method. But not sure how to do.

Upvotes: 2

Views: 1596

Answers (1)

Kaushal28
Kaushal28

Reputation: 5557

define start variable public, so you can access it from everywhere, as following:

public class AlphaSwap {
static int start = 0;
public static void main(String[] args) {
    String input[] = { "a", "b", "c", "_" };
   // int start = 0;
    int end = input.length - 1;

    AlphaSwap alphaSwap = new AlphaSwap();
    alphaSwap.swapFirst(input, start, end);

    //swapLast(input, start, end);

    for (String string : input) {
        System.out.println(string);
    }
    System.out.println(start);
    System.out.println(end);
}

private void swapFirst(String[] input, int i, int j) {
    String temp = input[i];
    input[i] = input[j];
    input[j] = temp;
    start++;
}
}

Upvotes: 3

Related Questions