• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

What is the alternate method for string.format method

 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 80057
409
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic