Having trouble with my code.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fungi
    New Member
    • Apr 2007
    • 3

    #1

    Having trouble with my code.

    I am write a program rotate()
    This method is supposed to bring the the # of end letters to the front based on the user input

    for example:
    String word = "hellos";
    tester.rotate(w ord,1); results in shello

    tester.rotate(w ord,5); results in hello [which would be the limit because hello has word length of 5]
    The following is the code that I wrote to rotate once and so on.
    I am working on making the code general and so specific such as if I say rotation = rotationable and let the user try different int values based on the word length. For some reason, my general code is not really working and I need help

    if (rotation == 1)
    {
    for (int i = word.length()-1; i>=word.length( )-1; i--)
    {
    rotated = rotated + word.charAt(i);
    }
    for (int i = 0; i<=word.length( )-2; i++)
    {
    rotated = rotated + word.charAt(i);
    }
    }
    System.out.prin tln(tester.rota te(word, 1));

    I cannot seem to come up with a code that will let me input any int value instead of 1 with out saying rotation == 1 in my real code.

    Answer: shello

    If you want to see what I am working on, I will send it.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Allow me to show you quite a different (and more powerful) approach; suppose
    you want to do this AAAAABBB ---> BBBAAAAA, i.e. you want to move the
    last n == 3 characters to the front. For notational convenience let aaaaa be the
    reverse of the sequence AAAAA. Here are the steps involved:

    1) reverse the entire string:

    AAAAABBB ---> bbbaaaaa

    2) reverse the first three characters:

    bbbaaaaa ---> BBBaaaaa

    3) reverse the last five characters:

    BBBaaaaa ---> BBBAAAAA

    All you have to do now is check the substring() method in the String class and
    the reverse method in the StringBuffer class.

    kind regards,

    Jos

    Comment

    Working...