-1

I am attempting to create a program that will take in a simple password and generate a newer, more complex password with certain characters being changed to special characters e.g(s == $). I've got this done but I would like to have 50% of the remaining characters Uppercase and 50% of them lowercase e.g(p@$$w0rd -> p@$$W0rD). Any ideas on how this would be done? passwordBeginning is a class holding the original simplified password. This is what I've got so far

public String getPassword() {
    String temp = passwordBeginning.getPassword();
    char[] chars = temp.toCharArray();
    for(int i = 0;i<chars.length;i++) {
        if(chars.length % 2 == 0) {
            chars[i] = Character.toUpperCase(chars[i]);
            i++;
        }
        if(chars.length % 2 >= 1) {
            chars[i] = Character.toLowerCase(chars[i]);
        }
  } 
        String revert = new String(chars);
        temp = revert;
    
    return temp;
  • why is `String revert = new String(chars);` in your for loop? – Scary Wombat Jan 31 '22 at 00:54
  • Great. So what's the question? Stack Overflow uses a Question & Answer format, which implies that you should be asking a question, rather than posting code and then crossing your arms while waiting for other people to say something. Ask something or expect nothing -- those are your choices. – MarsAtomic Jan 31 '22 at 00:56
  • This expression (`if(chars.length % 2 == 0)`) only depends on the length of the string, which doesn't change as you loop through the string. So it will do the same thing throughout the loop – Erwin Bolwidt Jan 31 '22 at 01:08
  • you are telling that your goal is to divide a string by half, whilst in your code, we can see `chars.length % 2 == 0` - actually that condition checks whether the given string is of even length – Alexander Ivanchenko Jan 31 '22 at 01:11

1 Answers1

0

Your code will uppercase and lowercase depending on the total length of the string. Instead, you want to look at your iteration variable.

public String getPassword() {
    String temp = passwordBeginning.getPassword();
    char[] chars = temp.toCharArray();
    for (int i = 0;i<chars.length;i++) {
        if (i % 2 == 0) {
            chars[i] = Character.toUpperCase(chars[i]);
        }
        else {
            chars[i] = Character.toLowerCase(chars[i]);
        }
    } 
    return new String(chars);
}

You had a spurious i++ in there.

Learn to use StringBuilder instead of manipulating the array of chars.

AgilePro
  • 5,588
  • 4
  • 33
  • 56