Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default printing string backwards and printing every other

    i am having trouble with a problem. i have been first trying to convert a string, backwards. here is a way that my book has it:

    String backwards = "testing!!!!!";
    printReversed(backwards);

    why doesn't this work?

    also, in this statement, what does this mean?: for (i = 0; i < length; i+=2)... you add 2 to every i?
    and why can't you have "i<=length"... i saw this on another post here, but didn't quite understand... i did get the same "out of bounds" error message... i thought that it was the int type at first.

    thanks,

    droidus
    Last edited by droidus; 02-24-2011 at 01:34 AM.

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Quote Originally Posted by droidus View Post
    String backwards = "testing!!!!!";
    printReversed(backwards);

    why doesn't this work?
    You seriously expect an answer with such little information provided? Crystal ball says the printReversed method does not exist.

    also, in this statement, what does this mean?: for (i = 0; i < length; i+=2)... you add 2 to every i?
    Yes.

    and why can't you have "i<=length"... i saw this on another post here, but didn't quite understand... i did get the same "out of bounds" error message
    If this is in relation to a string or an array, then you have to remenber that they are 0 based. So for a String with a length of 5 the characters are located at 0 - 4. If you try and access the character at position equal to length, it does not exist. hence you always loop to less than length. That is 4 is less than 5 OK. Then after increment to 5, 5 is not less than 5 so loop exits.

  3. #3
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Exclamation

    I get an out of bounds error. Also, how do i store my results from the substring, to a variable, such as reverse1? Also, if someone could answer my questions in my coding, that would be great! :)

    Java Code:
    	String creditCardNumber;
    	
    	//Prompts user for the 8-digit credit-card number
    	Scanner in = new Scanner(System.in);
    	System.out.println("What is your 8-digit credit card number (exclude spaces)?: ");
    	creditCardNumber = in.next();
    
    	int i;
    	int length = creditCardNumber.length();
    	 
    	for (i = 7; i < length; i-=2)
    	 	{
        	System.out.println(creditCardNumber.substring(i, i+1)); //what is this substring "i" and "i+1"?
        	}
    	String reverse1 = (creditCardNumber.substring(i, i+1)); /*this won't work since it is out of the "for" statement, would it?  
    	But if i put it in the statement, it would execute and print this out every time...*/
    	
    	//We then add up the numbers in the reverse string.  How can this be done?  charAt() for each number?
    	
    	if (length<8){	
    	System.out.println("Error: Your number is only " + length + " characters long.");
    	}
    	
    	for (i = 8; i < length; i-=2) //this will get the rest of the numbers (every other one).
    	 	{
        	System.out.println(creditCardNumber.substring(i, i+1));
        	}
    	String reverse2 = (creditCardNumber.substring(i, i+1));//We store this value to do math with; doubling digits, and adding all of those digits

  4. #4
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by droidus View Post
    I get an out of bounds error. Also, how do i store my results from the substring, to a variable, such as reverse1? Also, if someone could answer my questions in my coding, that would be great! :)

    Java Code:
    	int length = creditCardNumber.length();
    	 
    	for (i = 7; i < length; i-=2)
    	 	{
        	System.out.println(creditCardNumber.substring(i, i+1)); //what is this substring "i" and "i+1"?
        	}
    The comments indicate that this is not your code; throw it away because the above doesn't make any sense; when you steal/borrow code, steal/borrow correct working code and not this crap.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

    Default Make use of StringBuffer

    Why can't you try something like this rather than going for complicated stuffs.

    Java Code:
    String forwardString = "philadelphia";
    String reverseString = new StringBuffer(forwardString).reverse().toString();
    System.out.println(reverseString);

  6. #6
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default

    ok, but i also need to read every other character, backwards, then set to a variable, which was what i was trying to do above.

  7. #7
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Is it really so hard to write a few lines? The StringBuilder example is correct, but it assigns an object that has to be disposed by garbage collection, and that isn't very good practice.
    Java Code:
    String original = "hello", reversed = "";
    for(int i = 0; i < original.length(); i++) {
      reversed = original.charAt(i)+reversed;
    }
    Ever seen a dog chase its tail? Now that's an infinite loop.

  8. #8
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

    Default

    The StringBuilder example is correct, but it assigns an object that has to be disposed by garbage collection
    Hello m00nchile,
    Please correct me if I'm wrong, because I'm new to Java.
    The string appending solution suggested by you will also create objects each time a string is appended. First the string reference "reverse" points to a string object which has the value "". Next when the appending happens, string reference "reverse" will disconnect from the earlier object in the string literal pool and points to the new object with value "h". Next "reverse" abandons "h" and points to "eh" and so on.
    I'm atleast sure this is the case when concat method is used. I hope it's the same with "+" operator too.

  9. #9
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    When using String literals, it uses a so-called String pool, where the literals are stored. Also, since the goal of the method is to reverse a string, you can't count the String reverse as an additional object. Also, I wasn't saying your example was wrong in any way, just that it's good practice to think about where do you assign new objects and where you don't. If this method is used once in a blue moon, then sure, one extra object to be disposed by garbage collection has no impact on performance. If this method is called a few times per second, the number of assigned objects rises to critical levels, and can cause your app to freeze every few seconds, since the garbage collection cycle has a lot of work to do.
    Here's a little example of the String pool in action:
    Java Code:
    public class StringExample {
      public static void main(String[] args) {
        String a = "hello";
        if(a == "hello") System.out.println("yes 1");  //returns true, because String a points to the "hello" string in pool
        String b = "hello"
        if(a == b) System.out.println("yes 2");  //again, true, b points to the same "hello" string in pool as a
        String c = new String("hello");
        if(a == c) System.out.println("yes 3"); //returns false, since c doesn't point to the "hello" in the pool, but assigns a new string object
        if(a.equals(c)) System.out.println("yes equals"); //of course true, since a and c are the same by characters
      }
    }
    Even though you shouldn't use == to compare Strings (== tests object equality, ie do both references point to the same location in memory), this example gives you an idea about how Java handles String literals. At the line String b = "hello", no assignment happens, since "hello" is already in the pool.
    Last edited by m00nchile; 02-26-2011 at 10:34 AM.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  10. #10
    YAY
    YAY is offline Member
    Join Date
    Feb 2011
    Posts
    20
    Rep Power
    0

    Default

    Simple reversing string
    Java Code:
    String str1="My string";
    String str2="";
    for(int i = str1.length() - 1; i >= 0; i--)
       str2 += str1.charAt(i);

  11. #11
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by YAY View Post
    Simple reversing string
    Java Code:
    String str1="My string";
    String str2="";
    for(int i = str1.length() - 1; i >= 0; i--)
       str2 += str1.charAt(i);
    This home brew solution creates 10 String objects and 10 StringBuffer objects. Why not stick to the class that can do the job efficiently (StringBuffer or StringBuilder) as was shown in a previous reply?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  12. #12
    YAY
    YAY is offline Member
    Join Date
    Feb 2011
    Posts
    20
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    This home brew solution creates 10 String objects and 10 StringBuffer objects. Why not stick to the class that can do the job efficiently (StringBuffer or StringBuilder) as was shown in a previous reply?

    kind regards,

    Jos
    Just compile and run, you'll see what is happenning
    Java Code:
    class a
    {
    		public static void main(String[] args)
    		{
    			String str1="My string"; 
    			String str2=""; 
    			for(int i = str1.length() - 1; i >= 0; i--) 
    			{	
    				str2 += str1.charAt(i);
    				System.out.println(str2);
    			}
    		}
    }
    It's just appending to empty string

  13. #13
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by YAY View Post
    Just compile and run, you'll see what is happenning
    It's just appending to empty string
    I know what is happening; a + operator applied to at least one String operand creates a StringBuffer and does the appending using that StringBuffer. The result is transformed back to a String again, so your example creates 10 Strings and 10 StringBuffers; don't do it that way.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

  15. #15
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default int to string, and then getting length

    i am trying to convert integers to a string:

    Java Code:
    Integer.toString (doubledNextDigit); //gets all of the double digits, and puts them into a string
    	} 
    	
    	int length = doubledNextDigit.length;
    i get a dereference error. what does this mean? and how would i fix this?

  16. #16
    YAY
    YAY is offline Member
    Join Date
    Feb 2011
    Posts
    20
    Rep Power
    0

    Default

    Quote Originally Posted by subith86 View Post
    So, does that mean that concatination is O(n^2), builder and buffer are O(n)?

  17. #17
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by YAY View Post
    So, does that mean that concatination is O(n^2), builder and buffer are O(n)?
    Yes, try the following experiments and see for yourself:

    Java Code:
    String s= "";
    for (int i= 0; i < 1000000; i++)
       s+= "x";
    and this one:

    Java Code:
    StringBuider sb= new StringBuilder();
    for (int i= 0; i < 1000000; i++)
       sb.append("x");
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  18. #18
    YAY
    YAY is offline Member
    Join Date
    Feb 2011
    Posts
    20
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Yes, try the following experiments and see for yourself:

    Java Code:
    String s= "";
    for (int i= 0; i < 1000000; i++)
       s+= "x";
    and this one:

    Java Code:
    StringBuider sb= new StringBuilder();
    for (int i= 0; i < 1000000; i++)
       sb.append("x");
    kind regards,

    Jos
    OMG :eek:
    You're absolutely right...
    Sory for being such a moron...

  19. #19
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Java Code:
    Integer.toString (doubledNextDigit); //gets all of the double digits, and puts them into a string
    As long as you then assign the resulting String to a variable.
    i get a dereference error. what does this mean? and how would i fix this?
    The doubleNextDigit is a primitive. Primitives do not have methods, only classes do. What you are trying to do is the equivalent of
    Java Code:
    7.doStuff();
    which doesn't really make sense. You fix it by calling the method on an actual object and not your primitive.

  20. #20
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by YAY View Post
    OMG :eek:
    You're absolutely right...
    Sory for being such a moron...
    That all happens because Strings are immutable, e.g. when you want to append a a String on length m to a String of length n the JVM allocates a StringBuffer of length n+m, copies both Strings to it and finally creates a new String of length n+m; if you closely follow the steps the amount of memory needed is n+m+(n+m)+(n+m). If those first two Strings can be gc'd and the StringBuffer is gc'd the final memory taken is (n+m); you do that in a loop and you can see the fireworks ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Page 1 of 2 12 LastLast

Similar Threads

  1. Help in Printing
    By kirly in forum Advanced Java
    Replies: 3
    Last Post: 10-03-2011, 04:40 PM
  2. Printing
    By zzpprk in forum AWT / Swing
    Replies: 0
    Last Post: 01-20-2010, 12:25 PM
  3. printing an array of String through drawString
    By kaemonsaionji in forum New To Java
    Replies: 1
    Last Post: 02-23-2009, 05:38 PM
  4. Printing Help...
    By chiragkini in forum AWT / Swing
    Replies: 1
    Last Post: 02-17-2009, 07:07 AM
  5. Printing Example
    By Java Tip in forum SWT Tips
    Replies: 0
    Last Post: 07-11-2008, 05:41 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •