Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 help - reversing string input
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
whoareyou




PostPosted: Tue Apr 19, 2011 3:09 pm   Post subject: help - reversing string input

This "test" program is supposed to output a string that was inputted in reverse order. I can get it working, except it won't show the first letter. For example, if the string I input is "Hello", it outputs "olle". That's the first problem. The second problem is that when I set up a for loop to count from the last letter to the first, it displays a weird error message.

code:

java.lang.StringIndexOutOfBoundsException: String index out of range: 5
        at java.lang.String.charAt(Unknown Source)
        at Lool.main(Lool.java:26)


This is the actual code.

code:


// The "Lool" class.
import java.awt.*;
import hsa.Console;

public class Lool
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();

        String str;

        c.println ("Please type a sentence: ");
        str = c.readLine ();



        c.println (str);

        for (int i = str.length (); 0<= i  ; i--)
        {
            char ch;

            ch = str.charAt (i-1);

            c.print (ch);
            c.print (" ");
        }

        c.println ();

    } // main method
} // Lool class



Any help/suggestions would be appreciated Smile.
Sponsor
Sponsor
Sponsor
sponsor
DemonWasp




PostPosted: Tue Apr 19, 2011 3:14 pm   Post subject: RE:help - reversing string input

Java's Strings are indexed from 0. This means that the "first" character is 0, the second is 1, and the nth character is at index (n-1). Your loop seems to be working on the assumption that it can access index (n) of an n-characters-long string, which it can't -- it can only access up to index (n-1).

Edit: That's a pretty self-explanatory error message. If you read it, it's telling you that your String Index is Out of Bounds, and that caused an Exception. It tells you the exact line where it happened, and it even mentioned that you were looking at index 5. Given as the String is "Hello", index 0 is 'H', index 1 is 'e', ..., index 5 is out of bounds.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: