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); } }

25th Sep 2021, 2:19 AM
Solus
Solus - avatar
9 odpowiedzi
+ 2
@Nezuko Thanks a lot! Just adding the 'final' keyword did the trick.
25th Sep 2021, 4:33 PM
Solus
Solus - avatar
+ 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
25th Sep 2021, 9:55 AM
Rishi
Rishi - avatar
0
I executed your code in the code playground and it didn't give me any warning
25th Sep 2021, 2:26 AM
Rishi
Rishi - avatar
0
Code playground doesn't work. I'm using Eclipse with the Checkstyle plugin @Rishi
25th Sep 2021, 3:11 AM
Solus
Solus - avatar
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.
25th Sep 2021, 3:33 AM
Ipang
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
25th Sep 2021, 4:33 AM
Rishi
Rishi - avatar
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
25th Sep 2021, 7:28 AM
Rishi
Rishi - avatar
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?
25th Sep 2021, 8:16 AM
Rishi
Rishi - avatar
0
Aarti Agarwal I can't agree with you but okay =)
25th Sep 2021, 12:56 PM
Rishi
Rishi - avatar