Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: String reverse

  1. #1
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default String reverse

    Hi am trying to reverse a string

    Here is my code:
    import java.util.*;
     
    public class ReverseLettersInString {
    	public static void main (String[] args){
    		Scanner in = new Scanner (System.in);
    		String s;
    		System.out.printf ("Enter string\n");
    		s = in.nextLine();
     
    		for (int i= s.length()-1; i>0; i--)
    		{
    			System.out.printf ("%c", s.charAt(i));
    		}
    	}
     
    }

    PROGRAM OUTPUT:
    Enter string
    me
    e


    The program returns e instead of em


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: String reverse

    Look at the loop closely. Considering the input of the String 'me' - the length of 'me' is 2, the index of 'm' is 0, and 'e' is 1...will the loop ever reach 'm'?

  3. The Following User Says Thank You to copeg For This Useful Post:

    Java girl (April 20th, 2014)

  4. #3
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: String reverse

    Thanks a lot, I changed i>0 to i>=0 and it worked!

Similar Threads

  1. How to reverse a string array ?
    By craigjlner in forum Loops & Control Statements
    Replies: 9
    Last Post: December 3rd, 2013, 05:53 AM
  2. Replies: 9
    Last Post: February 26th, 2013, 11:36 AM
  3. Reverse a String
    By Mehwish-S in forum What's Wrong With My Code?
    Replies: 4
    Last Post: August 22nd, 2012, 09:03 AM
  4. Reverse String
    By WantHelp in forum What's Wrong With My Code?
    Replies: 7
    Last Post: July 5th, 2011, 06:14 AM
  5. Replies: 3
    Last Post: June 14th, 2009, 09:31 PM