Walter Straub
Walter Straub

Reputation: 83

Java program that prints a string backwards

I'm trying to write a program that takes a string, breaks it up into characters, and prints each character backwards. I sort of see what the problem is, I just am not sure how to fix it. Here is my code:

public static void main(String[] args) {
    //takes a string and prints all the letters backwards all on one line

    String fruit = "apple";
    backwards(fruit);
    }

public static void backwards(String theFruit) {
    int length = theFruit.length() - 1;
    int counter = 0;
    while(length > counter) {
        char theCharacter = theFruit.charAt(length);
        System.out.println(theCharacter);
        counter++;
    }
}

For some reason it just prints all one letter and I am not sure why.

Upvotes: 1

Views: 414

Answers (5)

antonpp
antonpp

Reputation: 2383

I think that the easiest approach for your task is to use StringBuilder class.

public static void backwards(String theFruit) {
    return new StringBuilder(theFruit).reverse().toString();
}

Upvotes: 1

Coding Champ
Coding Champ

Reputation: 36

You can use StringBuffer Class.

public static void main(String[] args) {
    StringBuffer fruit = new StringBuffer("apple");
    System.ouyt.println(fruit.reverse());
    }

Upvotes: 0

Shadow
Shadow

Reputation: 4016

The problem is that length doesn't change, and you are using the length for your println statement.

Instead of adding to counter at the end of your loop, subtract from length. You should then change your while to check that is >= counter:

while (length >= counter)
{
    System.out.println(theFruit.charAt(length));
    length--;
}

You could also change your loop and use a for loop instead:

for (int i = length; i >= 0; i--)
{
    System.out.println(theFruit.charAt(i));
}

Upvotes: 1

singhakash
singhakash

Reputation: 7919

Decrease the value of length

while(length >= counter) {
        char theCharacter = theFruit.charAt(length);
        System.out.println(theCharacter);
        length--;
}

with your approach you are printing the last character everytime because length value never changed

Demo

Upvotes: 0

Prashant
Prashant

Reputation: 2614

decrements the length in while loop. and don't increase counter variable.

as :

while(length >= counter) {
    char theCharacter = theFruit.charAt(length);
    System.out.println(theCharacter);
    length--;
}

Upvotes: 0

Related Questions