• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the alternate method for string.format method  RSS feed

 
Robert Jack
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.

   I am using string.format method which is used to add zero's.

   I set the roll number value is: 8123 and number of digits i used 8. This string.format method will return the value is 00008123.

   What is the alternate method for string.format

    String.format("%0" + 8 + "d", 8123l) --> 00008123



Thanks in advance.
 
Robert Jack
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
return String.format("%0" + totalDigits + "d", rollNumber);


Sonar qube tool saying the critical error
"Format specifiers should be used instead of string concatenation"

But i am getting the perfect result.

Please help me this.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I presume you mean alternative. I think you are right to say your method works, but it can be improved, so I don't think an alternative is necessary.
That second method of yours (lines 13‑15) behaves rather like a function and shou‍ld probably be marked static final. In that case you must also pass the number to be formatted as an argument. If the number is a long, always append the final L: 8123L. Don't use l because I can see the earlier number as 81231. You now have this sort of methodAs for the warning from the IDE etc. There comes a time when you have to bite the bullet and tell the IDE you do know what you are doing and I am going to ignore that warning
I you write yourself a utility class, you can put that method in the utility class and keep it for ever.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!