I thought I'd kind of ensured the generated password contained all the types of data (numerals, lowercase letters and uppercase ones). However, the validator disagrees with that, even though the code produces the output that seems to comply with the requirements... What am I missing?
package com.codegym.task.task32.task3204;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
/*
Password generator
*/
public class Solution {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream password = getPassword();
System.out.println(password.toString());
}
public static ByteArrayOutputStream getPassword() throws IOException {
StringBuilder sb = new StringBuilder();
int counter = 0;
boolean numeralAdded = false;
boolean lowCaseAdded = false;
boolean upperCaseAdded = false;
boolean noneAdded = !numeralAdded && !lowCaseAdded && !upperCaseAdded;
boolean allAdded = numeralAdded && lowCaseAdded && upperCaseAdded;
Random random = new Random();
while (counter != 8) {
if (noneAdded || allAdded) {
// if the sb is empty or all types are present,
// we safely choose a random type of data to be added
int type = 1 + (int) (Math.random() * 3);
if (type == 1) {
char randomLowCase = (char) (random.nextInt(26) + 'a');
sb.append(randomLowCase);
lowCaseAdded = true;
counter++;
} else if (type == 2) {
int randomNumeral = 1 + random.nextInt(4);
sb.append(randomNumeral);
numeralAdded = true;
counter++;
} else if (type == 3) {
char randomUpperCase = (char) (random.nextInt(26) + 'A');
sb.append(randomUpperCase);
upperCaseAdded = true;
counter++;
}
} else if (!numeralAdded) {
int randomNumeral = 1 + random.nextInt(4);
sb.append(randomNumeral);
numeralAdded = true;
counter++;
} else if (!lowCaseAdded) {
char randomLowCase = (char) (random.nextInt(26) + 'a');
sb.append(randomLowCase);
lowCaseAdded = true;
counter++;
} else if (!upperCaseAdded) {
char randomUpperCase = (char) (random.nextInt(26) + 'A');
sb.append(randomUpperCase);
upperCaseAdded = true;
counter++;
}
}
String password = sb.toString();
ByteArrayInputStream bais = new ByteArrayInputStream(password.getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (bais.available() > 0) {
int data = bais.read();
baos.write(data);
}
bais.close();
return baos;
}
}