Results 1 to 20 of 23
- 02-24-2011, 12:30 AM #1
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
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,
droidusLast edited by droidus; 02-24-2011 at 12:34 AM.
- 02-24-2011, 12:46 AM #2
You seriously expect an answer with such little information provided? Crystal ball says the printReversed method does not exist.
Yes.also, in this statement, what does this mean?: for (i = 0; i < length; i+=2)... you add 2 to every i?
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.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
- 02-24-2011, 03:56 PM #3
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
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
- 02-24-2011, 04:16 PM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,601
- Blog Entries
- 7
- Rep Power
- 17
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 02-24-2011, 04:22 PM #5
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
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);
- 02-24-2011, 05:33 PM #6
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
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, 07:13 PM #7
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
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.
- 02-26-2011, 04:30 AM #8
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
Hello m00nchile,The StringBuilder example is correct, but it assigns an object that has to be disposed by garbage collection
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, 09:22 AM #9
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
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:
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.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 } }Last edited by m00nchile; 02-26-2011 at 09:34 AM.
Ever seen a dog chase its tail? Now that's an infinite loop.
- 02-26-2011, 09:42 AM #10
Member
- Join Date
- Feb 2011
- Posts
- 20
- Rep Power
- 0
Simple reversing string
Java Code:String str1="My string"; String str2=""; for(int i = str1.length() - 1; i >= 0; i--) str2 += str1.charAt(i);
- 02-26-2011, 11:34 AM #11
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,601
- Blog Entries
- 7
- Rep Power
- 17
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 02-26-2011, 11:49 AM #12
Member
- Join Date
- Feb 2011
- Posts
- 20
- Rep Power
- 0
Just compile and run, you'll see what is happenning
It's just appending to empty stringJava 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); } } }
- 02-26-2011, 12:40 PM #13
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,601
- Blog Entries
- 7
- Rep Power
- 17
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,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 02-27-2011, 06:46 AM #14
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
Hi YAY,
I think the below link will clarify
StringBuilder vs StringBuffer vs String.concat - done right | kaioa.com
- 03-08-2011, 06:51 PM #15
Senior Member
- Join Date
- Feb 2011
- Posts
- 235
- Rep Power
- 3
int to string, and then getting length
i am trying to convert integers to a string:
i get a dereference error. what does this mean? and how would i fix this?Java Code:Integer.toString (doubledNextDigit); //gets all of the double digits, and puts them into a string } int length = doubledNextDigit.length;
- 03-08-2011, 07:13 PM #16
Member
- Join Date
- Feb 2011
- Posts
- 20
- Rep Power
- 0
- 03-08-2011, 07:30 PM #17
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,601
- Blog Entries
- 7
- Rep Power
- 17
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 03-08-2011, 08:11 PM #18
Member
- Join Date
- Feb 2011
- Posts
- 20
- Rep Power
- 0
- 03-08-2011, 09:04 PM #19
As long as you then assign the resulting String to a variable.Java Code:Integer.toString (doubledNextDigit); //gets all of the double digits, and puts them into a string
The doubleNextDigit is a primitive. Primitives do not have methods, only classes do. What you are trying to do is the equivalent ofi get a dereference error. what does this mean? and how would i fix this?
which doesn't really make sense. You fix it by calling the method on an actual object and not your primitive.Java Code:7.doStuff();
- 03-09-2011, 07:57 AM #20
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,601
- Blog Entries
- 7
- Rep Power
- 17
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,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
Help in Printing
By kirly in forum Advanced JavaReplies: 3Last Post: 10-03-2011, 03:40 PM -
Printing
By zzpprk in forum AWT / SwingReplies: 0Last Post: 01-20-2010, 11:25 AM -
printing an array of String through drawString
By kaemonsaionji in forum New To JavaReplies: 1Last Post: 02-23-2009, 04:38 PM -
Printing Help...
By chiragkini in forum AWT / SwingReplies: 1Last Post: 02-17-2009, 06:07 AM -
Printing Example
By Java Tip in forum SWTReplies: 0Last Post: 07-11-2008, 04:41 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks