0

I have following code in Java.

private final int level1BallCount = 5;
private final int level2BallCount = 10;
private final int level3BallCount = 15;
private final int level4BallCount = 20;
private final int level5BallCount = 25;
private final int level6BallCount = 30;
private final int level7BallCount = 35;
private final int level8BallCount = 40;
private final int level9BallCount = 45;
private final int level10BallCount = 50;
private final int level11BallCount = 55;
private final int level12BallCount = 60;

Now it all functions properly, however I would like to know if there is some easier way like lists for this, because when I type getters and setters for this, code goes really huge.

Anyone with a better idea how to do this?

2
  • 1
    if its a constant better use a separate file or just create a Enum so that it is easy to maintain. Commented Dec 4, 2016 at 11:22
  • Is the BallCount multiple of 5 or x factor always ? Commented Dec 4, 2016 at 11:26

3 Answers 3

1

I'd do in this way:

private final int [] levelBallCounts = {5,10,15,20,25,30,35,40,45,50,55,60};

public int getLevelBallCountAtPos(int pos){
    return levelBallCounts[pos-1];
}

or simply (without using levelBallCounts array):

public int getLevelBallCountAtPos(int pos){
    return pos*5;
}

Usage:

System.out.println(getLevelBallCountAtPos(1)); //returns 5
System.out.println(getLevelBallCountAtPos(4)); //returns 20
System.out.println(getLevelBallCountAtPos(12)); //returns 60
Sign up to request clarification or add additional context in comments.

1 Comment

Please OP, Go with this answer. Was gonna type this but he beat me to it.
0

If there is some easier way like lists for this, because when I type getters and setters for this, code goes really huge ?

Not really, you don't need huge list of getter methods for this. You can use enum type for your BallCounts as shown below with a single get method as shown below:

public enum BallCounts {

        LEVEL1(5), LEVEL2(10);//add other levels

        private int level;

        private BallCounts(int count) {
            this.level = level;
        }

        //Single getter method
        public int getBallCountLevel() {
            return level;
        }
    }

1 Comment

Enum was the best thing to go for this one. I made an array of enums and accessed them using constructor :-)
0

Even putting in a List can be nice, it depends on what you prefer or need.

Declaration:

private static final List<Integer> levelBallCounts;
static {
   levelBallCounts = new ArrayList<>();
   levelBallCounts.add(5);
   levelBallCounts.add(10);
   [...]
}
[...]

Call with:

levelBallCounts.get(...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.