Possible Duplicate:
How do I compare strings in Java?
(This may be a duplicate, I was not aware of .equals
. My apologies.)
I was messing around in Java today when I decided to make a 4 character string generator. I have the program generate every possible combination of characters that I defined. This isn't for a project, I just wanted to see if this was possible. My problem lies with the string checking. I'll post the code first.
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] chars = text.toCharArray();
String name = "Mike";
String pass;
outerLoop:
for (int a = 0; a < chars.length; a ++) {
for (int b = 26; b < chars.length; b++) {
for (int c = 26; c < chars.length; c++) {
for (int d = 26; d < chars.length; d++) {
pass = chars[a]+""+chars[b]+""+chars[c]+""+chars[d];
System.out.println(pass);
if (pass == name){
System.out.print("password");
break outerLoop;
}
}
}
}
}
The nested if
will check if pass
is equal to Mike. If it is, then it prints password and will break the for loop.
- Is
pass = chars[a]...
the correct way to do this? When I tested it without theif
, I had it print out pass and it printed all of the combinations correctly. It did printMike
, but it did not catch in theif
. - I also changed the nested
for
loops so they start with the lower case because the program was taking a while to run when I made minor changes.