Reputation:
In my application, I have many IF statements that could be optimizing, but for the life of me can't work out a good possible solution without errors.
My current code:
if (User_XP > -1){User_level.setText("1");Minimum_Level= Level1; Maximum_level = Level2;}
if (User_XP > Level1){User_level.setText("1");Minimum_Level= Level1; Maximum_level = Level2;}
if (User_XP > Level2){User_level.setText("2");Minimum_Level = Level2; Maximum_level = Level3;}
if (User_XP > Level3){User_level.setText("3");Minimum_Level = Level3; Maximum_level = Level4;}
if (User_XP > Level4){User_level.setText("4");Minimum_Level = Level4; Maximum_level = Level5;}
if (User_XP > Level5){User_level.setText("5");Minimum_Level = Level5; Maximum_level = Level6;}
if (User_XP > Level6){User_level.setText("6");Minimum_Level = Level6; Maximum_level = Level6;}
if (User_XP > Level7){User_level.setText("7");Minimum_Level = Level7; Maximum_level = Level6;}
if (User_XP > Level8){User_level.setText("8");Minimum_Level = Level8; Maximum_level = Level6;}
if (User_XP > Level9){User_level.setText("9");Minimum_Level = Level9; Maximum_level = Level6;}
The idea of it is to work out a users level from a game, and from that create a percentage. But this area of coding is really not efficient as it can create multiple errors, anyone got any tips on a possible solution? Please ask if more information is needed.
Upvotes: 0
Views: 1087
Reputation: 582
In such cases I prefer making a static [not the java key word] propertiesfile/map/table and store the details in the properties,map or table. And then at run time read from the map and set the appropriate values or do things. This help is expansion without coding by simply adding values to
Upvotes: 0
Reputation: 82375
Why not do something more generic?...
if (User_XP > Minimum_Level) {
User_level.setText(Integer.toString(++Minimum_Level));
}
Of course if need the min/max instead of just doing a calculation..
if (User_XP > Minimum_Level) {
User_level.setText(Integer.toString(++Minimum_Level));
Maximum_Level = Minimum_Level + 1;
}
Then you could add in bounds checking before hand if you want to limit the absolute number if levels like if(Minimum_Level == 10) return; //Too much awesome!
Upvotes: 1
Reputation: 44919
Perhaps store your level experience requirements in an array and use a loop.
int[] levels = new int[] { -1, Level1, Level2, Level3 };
int level;
for (level = 0; level < levels.length && userXp < levels[level]; level++) { }
int minLevel = levels[level];
int maxLevel = levels[level + 1];
userLevelText.setText(Integer.toString(minLevel));
Upvotes: 2
Reputation: 12465
It seems like User_level.setText(String.valueOf(User_XP-1);Minimum_Level = User_level; Maximum_level = User_XP;
or something in that lines will do the job. The point is there seems to be some logic there, you should be able to eliminate the if statement all together.
Upvotes: 0