简体   繁体   中英

Increment primitive local variable by calling different methods

I'm solving a college project in Java where we can't (or it is not recommended to...) use global variables. If we could use it it would be easier. The thing is, I'm having troubles with a primitive variable (an integer that acts as a counter) that must be incremented every time that method is invoked.

For example:

public static void main... {
int rows = 0;
int[][] array = new int[24][2];
}

public static int readFile... (int rows, ...) {
...
...
...
rows++; (say here rows = 20);
return rows;
}

public static int addTeam... (int rows, ...) {
(method without for/while)
...
...
...
rows++;
return rows;
}

There are more methods. Now I use a switch where if I press say 1, the first method is invoked and so on. I want to press 2 three times, so that the second method gets invoked 4 times and the integer rows, thus, gets incremented until 23.

With a global variable this is easy, but without them how can I do it? No matter how many times I call the second method, the primitive (integer) "rows" won't change (I assume that's because it is a primitive, so it won't change like an array, which isn't a primitive).

I cannot use anything like lists, or objects (or even the this keyword), as this is an introduction to programming.

Possible option is to use switch and assign row value each time after method called:

int rows = 0;
...
case 1:
    rows = method1(rows, _);
    break;
case 2:
    rows = method2(rows, _);
    break;
 //so on

A more Object oriented solution: use a class to represent and save the data. Example, assuming you want to represent a collection of teams:

public class Teams {

    private int rows = 0;
    private int[][] array = new int[24][2];  // TODO use constant

    public int size() {
        return rows;
    }

    public void readFile(...) {
        // possible in a loop
        ...
        rows++;// call or addTeam(...);
    }

    public void addTeam(...) {
        ...
        rows++;
    }

    // more methods
}

Not ideal, based on questions code. (eg have a class Team to represent each team, using List instead of arrays, ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM