Issue With Removing Characters
My code is supposed to remove all of the repeated letters in Keyword1 and rewrite the String as Keyword12 (without any repeats), but it's not working.
Here's my code:
public static void main(String [] args){
// Code goes here
Scanner scan = new Scanner(System.in);
System.out.println("Write first keyword");
String Keyword1 = scan.nextLine();
String Keyword12 = Keyword1.substring(0,1);
for(int x = 1; x<Keyword1.length(); x++){
boolean b = true;
for(int y=0; y<Keyword12.length(); y++){
if (Keyword1.charAt(x) == Keyword12.charAt(y))
b=false;
}
if (b=true)
Keyword12 = Keyword12+Keyword1.charAt(x);
System.out.println(Keyword12);
}
System.out.println(Keyword12);
}
How come when I type in the word apple, it returns "apple" instead of "aple"?
Thanks a bunch!
Re: Issue With Removing Characters
If it always adds the letters, check and make sure your boolean is being set and assigned correctly. Throw in some println(b) statements to double check b's value is what you think it should be in your if statements.
Re: Issue With Removing Characters
ahh I figured it out, it was because my if(b=true) should have been if(b==true)
Thanks, Shoss!
Re: Issue With Removing Characters
Quote:
Originally Posted by
ezkatz19
ahh I figured it out, it was because my if(b=true) should have been if(b==true)
Thanks, Shoss!
No. It should beComparing a boolean to true or false is pointless, redundant and leads to just the mistake you experienced. Lose the habit and test the boolean itself, not its equivalence to true -- which just adds a useless step.
db
Re: Issue With Removing Characters
Ahh. I've been learning Java for just over a month, so cut me some slack, I didn't know that you could do that. Don't be a jackass and command, be suggestive.
Re: Issue With Removing Characters
Quote:
Originally Posted by
ezkatz19
Ahh. I've been learning Java for just over a month, so cut me some slack, I didn't know that you could do that. Don't be a jackass and command, be suggestive.
He is suggesting not demanding, and someone who is not quite so thin-skinned would have appreciated his taking an interest in furthering your Java education, would have thanked him for the help rather than antagonize him, and any others who read your remarks and who might have helped you in the future. Nice going there bucko.
Re: Issue With Removing Characters
You're right. I'm mad at something else right now, and I was wrongfully taking it out on you, DarrylBurke. I just didn't like the way you said "No. It should be" and "Lose."
Thanks, both.