1

I am trying to make an application that will reverse a string using a while loop. Just wondering if I am on the right path or not. So I thought I would make a while loop to determine how many chars i should make. Then I would just print them in reverse in the console.

Here is my code so far. Any help would be appreciated.

    // Get the text from the input from the user
    // Outputs it to the Text area 
    // Uses while loop to calculate how many chars to create    

    String Startword = txfInput.getText();


    int LengthOfWord = Startword.length();
    int Counter      = 1;



    while (Counter <= LengthOfWord) 

    {            

        // Creates amounts of chars based off the counter





        Counter = Counter +1 ;


    }

Any suggestions?

  • http://stackoverflow.com/questions/2612976/printing-reverse-of-any-string-without-using-any-predefined-function – SatyaTNV Feb 07 '16 at 12:39
  • @Satya The question specifies a while loop. So you can't point to any question, as that has 33 answers, and I guess I didn't see any on the first page with a while loop. If you see any answer which uses a while loop, then share a link to it. – dryairship Feb 07 '16 at 12:43

4 Answers4

0

You just need to add a character to the reverse String after every iteration, like this:

String Startword = txfInput.getText();
String rev="";

int LengthOfWord = Startword.length();
int Counter      = 1;

while (Counter <= LengthOfWord) 
{            
    rev=Startword.charAt(Counter-1)+rev; // Add a character to rev.
    Counter = Counter +1 ;

}

System.out.println(rev);
dryairship
  • 6,022
  • 4
  • 28
  • 54
0

Might be easier to do with a char array:

char[] output = new char[Startword.length];
for(int i = 0; i < Startword.length; i++){
    output[i] = Startword.charAt(Startword.length - i - 1);
}
String rev = new String(output);
SOFe
  • 7,867
  • 4
  • 33
  • 61
0

Just use a for loop..

String reverse = "";
for (int i = word.length()-1; i>=0; i--)
{
 reverse += word.charAt(i); 
}

if you want a while... then

while(i >= 0)
{
reverse += word.charAt(i); 
i--;
}
gallickgunner
  • 472
  • 5
  • 20
0
Scanner input = new Scanner(System.in);
    String s=input.nextLine();

    char[] stringArray;

    stringArray = s.toCharArray();

            int temp;
            int low=0;
            int high=stringArray.length-1;
            while(low<high){
                temp= stringArray[low];
                stringArray[low] = stringArray[high];

                System.out.print(stringArray[low]);


                low ++;
                high--;
            }

check this out

Akhil
  • 78
  • 12