Results 1 to 4 of 4
- 11-27-2008, 10:39 PM #1
Member
- Join Date
- Nov 2008
- Posts
- 3
- Rep Power
- 0
JAVA: String char removal with nested loop
I'm trying to make a nested loop which will search for and remove chars from a string. The keyword contains six letters, alphabet of course is 26. Can anyone show me what I'm doing wrong? The second loop works fine to remove one char, but I need it to remove all six, so that only the letters of the alphabet remain that are not in the keyword.
Java Code:for (int j = 0; j < keyword.length(); j++) letter = keyword.charAt(j); for (int i = 0; i < alphabet.length(); i ++) if (alphabet.charAt(i) != letter) r += alphabet.charAt(i);
- 11-28-2008, 12:02 AM #2
Suggestions...
- Well... the first thing that stands out is a total lack of curly brackets "{}". Even if you have a one-liner after a "for" or "if", it's good to use them... you avoid headaches later on.
Java Code:for (int j = 0; j < keyword.length(); j++) [COLOR="Red"]{[/COLOR] letter = keyword.charAt(j); for (int i = 0; i < alphabet.length(); i ++) [COLOR="red"]{[/COLOR] if (alphabet.charAt(i) != letter) [COLOR="red"]{[/COLOR] r += alphabet.charAt(i); [COLOR="red"]}[/COLOR] [COLOR="red"]}[/COLOR] [COLOR="red"]}[/COLOR]- Next, you're comparing strings using equality operators (==, !=). Since you're comparing strings it's better to use the String class methods like .equals() or .compareTo():
String (Java Platform SE 6)
Luck,
CJSLChris S.
Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.
- 11-28-2008, 12:40 AM #3
Member
- Join Date
- Nov 2008
- Posts
- 3
- Rep Power
- 0
Thanks, that's useful. Sorry I forgot to mention that "letter" is a char so I can't use the String API methods, I think.
- 11-28-2008, 02:09 AM #4
Similar Threads
-
I want to recreate the method drawRect with a nested for-loop
By chelseacortez in forum Java 2DReplies: 4Last Post: 09-05-2008, 04:47 PM -
char to string
By kian_hong2000 in forum New To JavaReplies: 2Last Post: 08-25-2008, 01:51 PM -
nested for loop question
By javabob in forum New To JavaReplies: 3Last Post: 05-20-2008, 11:00 PM -
Char to String in java
By trill in forum New To JavaReplies: 1Last Post: 08-01-2007, 01:42 PM -
Nested For Loop
By yuchuang in forum New To JavaReplies: 1Last Post: 07-08-2007, 01:11 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks