# printing string backwards and printing every other

Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last
• 02-24-2011, 01:30 AM
droidus
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
• 02-24-2011, 01:46 AM
Junky
Quote:

Originally Posted by droidus
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.

Quote:

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

Quote:

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.
• 02-24-2011, 04:56 PM
droidus
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! :)

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```
• 02-24-2011, 05:16 PM
JosAH
Quote:

Originally Posted by droidus
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! :)

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
• 02-24-2011, 05:22 PM
subith86
Make use of StringBuffer
Why can't you try something like this rather than going for complicated stuffs.

Code:

```String forwardString = "philadelphia"; String reverseString = new StringBuffer(forwardString).reverse().toString(); System.out.println(reverseString);```
• 02-24-2011, 06:33 PM
droidus
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.
• 02-24-2011, 08:13 PM
m00nchile
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.
Code:

```String original = "hello", reversed = ""; for(int i = 0; i < original.length(); i++) {   reversed = original.charAt(i)+reversed; }```
• 02-26-2011, 05:30 AM
subith86
Quote:

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.
• 02-26-2011, 10:22 AM
m00nchile
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:
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.
• 02-26-2011, 10:42 AM
YAY
Simple reversing string
Code:

```String str1="My string"; String str2=""; for(int i = str1.length() - 1; i >= 0; i--)   str2 += str1.charAt(i);```
• 02-26-2011, 12:34 PM
JosAH
Quote:

Originally Posted by YAY
Simple reversing string
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
• 02-26-2011, 12:49 PM
YAY
Quote:

Originally Posted by JosAH
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
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
• 02-26-2011, 01:40 PM
JosAH
Quote:

Originally Posted by YAY
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
• 02-27-2011, 07:46 AM
subith86
• 03-08-2011, 07:51 PM
droidus
int to string, and then getting length
i am trying to convert integers to a string:

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?
• 03-08-2011, 08:13 PM
YAY
Quote:

Originally Posted by subith86

So, does that mean that concatination is O(n^2), builder and buffer are O(n)?
• 03-08-2011, 08:30 PM
JosAH
Quote:

Originally Posted by YAY
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:

Code:

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

Code:

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

Jos
• 03-08-2011, 09:11 PM
YAY
Quote:

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

Code:

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

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...
• 03-08-2011, 10:04 PM
Junky
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.
Quote:

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
Code:

`7.doStuff();`
which doesn't really make sense. You fix it by calling the method on an actual object and not your primitive.
• 03-09-2011, 08:57 AM
JosAH
Quote:

Originally Posted by YAY
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
Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last