Created
January 14, 2017 13:45
-
-
Save vpiotr/4c2ed5610c1e329dc33f8a7af3a38e91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package passgen; | |
import java.util.Random; | |
import java.util.Scanner; | |
/** | |
* Exercise 37 from "Exercises for programmers". | |
* @author Piotr Likus | |
*/ | |
public class PassGen { | |
static Random rnd = new Random(); | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
System.out.println("--- Password generator ---"); | |
int passLen = readInt(sc, "What's the minimum length?"); | |
int specCount = readInt(sc, "How many special characters?"); | |
int numCount = readInt(sc, "How many numbers?"); | |
int cnt = 5; | |
while(cnt-- > 0) { | |
String passwd = generatePassword(passLen, specCount, numCount); | |
System.out.println("Your password is:"+passwd); | |
} | |
} | |
private static int readInt(Scanner sc, String prompt) { | |
System.out.println(prompt); | |
return sc.nextInt(); | |
} | |
private static String generatePassword(int passLen, int specCount, int numCount) { | |
final String specialChars = "!@#$%^&*()-=_+\\|"; | |
final String digits = "0123456789"; | |
final String alpha = "abcdefghijklmnopqrstvuwyzABCDEFGHIJKLMNOPQRSTVUWXYZ"; | |
StringBuilder res = new StringBuilder(); | |
int specAdded = 0; | |
int numAdded = 0; | |
while(res.length() < passLen) { | |
CharType ct = PassGen.randomCharType(); | |
switch(ct) { | |
case SPECIAL: { | |
if (specAdded < specCount) { | |
res.append(randomChar(specialChars)); | |
specAdded++; | |
break; | |
} | |
} | |
case DIGIT: { | |
if (numAdded < numCount) { | |
res.append(randomChar(digits)); | |
numAdded++; | |
break; | |
} | |
} | |
default: { | |
res.append(randomChar(alpha)); | |
} | |
} | |
} | |
return res.toString(); | |
} | |
private static CharType randomCharType() { | |
int idx = rnd.nextInt(3); | |
switch(idx) { | |
case 0: return CharType.SPECIAL; | |
case 1: return CharType.DIGIT; | |
default: | |
return CharType.ALPHA; | |
} | |
} | |
private static char randomChar(String text) { | |
int idx = rnd.nextInt(text.length()); | |
return text.charAt(idx); | |
} | |
private enum CharType { | |
SPECIAL, | |
DIGIT, | |
ALPHA | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment