Win a copy of Grokking Bitcoin this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

Java beginner problem with substring  RSS feed

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I am trying to create a program where it asks the user for their first, middle and last name and then it prints their initials but this is not working. Here is what I have so far:



It simply print the whole firstname.middlename.lastname

Help with solving this program is appreciated!
 
Rancher
Posts: 1943
15
Android Eclipse IDE Java Java ME
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to pass one more parameter, i.e. from 0 up to which it should substring

 
Marshal
Posts: 64131
215
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have  look at the substring() method and see how it works.

Please don't write lines as long as your line 8. Have a look in the old Sun Style Guide to see how to correct that.
 
Greenhorn
Posts: 25
2
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What Seastik Dey said.

Java API specifies that the "substring" method of the String class with one parameter only specifies the (0-based) start index of the substring to extract from the string: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-
The resulting string will last from that start index to the very end of the String.
Instead you need the overloaded two-parameter version of the same method, specifying the (0-based) end index as second parameter: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-int-

Swastik Dey's code should do the trick so all credits go to him.


Mike
 
Bartender
Posts: 700
10
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And to print just the initials, it might be better (or more clear) to use charAt(0) instead of substring(0,1).
 
look! it's a bird! it's a plane! It's .... a teeny tiny ad
Create Edit Print & Convert PDF Using Free API with Java
https://coderanch.com/wiki/703735/Create-Convert-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!