0

I have an assignment for school where I need to do some things with text. One of them being reversing a string.

Now I've got a while-loop that kind of works, but I have some questions about it.

if(drawRev){
  int i = textBoxInput.length();
  while(i>0){
    textRev += textBoxInput.substring(i-1,i);
    i--;       
    if(i==0){
     finalReversed = textRev;
     drawRev = false;        
     drawReverse = true;      
    }
  } 
}

So first thing I'd like to ask is: Why does the while-loop not stop when i reaches 0?

The boolean drawRev is true when I click a button but I have to manually make it false if i==0. I shouldn't have to do this right?

Second question I have is: How do I keep the reversed text to display it?

It does in fact reverse the text when I enter it, but it immediately turns into an empty string when it finishes.

I'm a beginning student and pretty new to programming in general, so keep it simple please!

If you'd like to see the whole code it's available here: http://pastebin.com/f1dW8b0Y

Sooi
  • 1
  • 2

2 Answers2

0

I've got it working. I tried to make it too complex.

Thanks to deamentiaemundi. This works:

if(drawRev){
  int i = textBoxInput.length();
  while(i>0){
    textRev += textBoxInput.substring(i-1,i);    
    i--;
  } 
}

Here's the working code for someone with a similar issue: http://pastebin.com/mQC9AwVD

Sooi
  • 1
  • 2
0

another way to reverse a string

$(document).ready( function(){
  var str = "test";
  var revstr = str.split("").reverse().join(""); //"test" to ['t','e','s','t'] to ['t','s','e','t'] to "tset"
  $(".test").text(revstr)
});

For reference: How do you reverse a string in place in JavaScript?

Community
  • 1
  • 1
schoolcoder
  • 1,546
  • 3
  • 15
  • 31