• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Help with StringBuffer methods zero-based pls!!

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello everyone,
I'm writing for the SCJP 310-055,
I've been trying to figure out why this code gives me as output: ..azba
how the f was removed??
I hope to get an answer to this little "code", that would help me a lot

Thanks very much!

class Polish{
public static void main(String []args){
int x = 4;
StringBuffer sb = new StringBuffer("..fedcba");
sb.delete(3,6);
sb.insert(3, "az");
if (sb.length()>6) x = sb.indexOf("b");
sb.delete((x-3), (x-2));
System.out.println(sb);
}
}
[ April 11, 2008: Message edited by: James O'connor ]
 
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Here is step by step what you get
class Polish{
public static void main(String []args){
int x = 4;
StringBuffer sb = new StringBuffer("..fedcba");
// . . f e d c b a
// indexes 0 1 2 3 4 5 6 7
sb.delete(3,6); // will remove indexes 3,4 and 5(6-1) only so the string becomes . . f b a
0 1 2 3 4

sb.insert(3, "az");// will insert "az" before position 3 --> . . f a z b a
if (sb.length()>6) x = sb.indexOf("b");
// sb.length = 7 so x = 5 ( ie b is at position 5 of the string)
sb.delete((x-3), (x-2));
// sb.delete(2,3) will remove indexe 2 only
. . f a z b a becomes . . a z b a

System.out.println(sb);
 
Umberto O'conner
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very very much!
Regards,
James
 
Die Fledermaus does not fear such a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic