0
Java: How to get rid of checkstyle magic number warning?
public class CharAt { public static void main(String[] args) { String name = "javatpoint"; int charPosition = 4; // <---- '4' is a magic number. How to fix? char ch = name.charAt(charPosition); System.out.println(ch); } }
9 Antworten
+ 2
@Nezuko
Thanks a lot! Just adding the 'final' keyword did the trick.
+ 1
Aarti Agarwal but I thought that a good practise is to keep the scope of variables only where they are used. It's a variant of the rule "global variables are dangerous". I think his code doesn't have any mistakes
0
I executed your code in the code playground and it didn't give me any warning
0
Code playground doesn't work. I'm using Eclipse with the Checkstyle plugin @Rishi
0
I don't use Eclipse nor the plugin, but just wondering whether there is such an option to enable/disable that in the plugin's configuration? I just read its home page now, and it says the plugin can be configured easily.
0
I don't understand the error. For example, if I define a variable like,
int max_cards_in_a_deck=52;
The compiler saying 52 is a magic number is senseless. Or should I do like this?
#define FIFTY_TWO 52
int max_cards_in_a_deck=FIFTY_TWO;
XD
0
Aarti Agarwal exactly what I got. But this is different. He's not using a magic number in his code. He is defining a variable with a value and getting a warning
0
Aarti Agarwal I recommend you refer the link you posted😗
"A magic number is a direct usage of a number in the code."
To avoid this, one has to define the number with some named variable. Like,
Bad practise(using magic numbers):
createDeckOfCards(52);
Good practise(without magic numbers):
int cards_in_a_deck=52;
createDeckOfCards(cards_in_a_deck);
To avoid the use of magic numbers, @Solus has defined the number with a name, and this is producing a warning.
Right?
0
Aarti Agarwal I can't agree with you but okay =)