What I'm trying to do is to generate a random string of numbers E.G 2645237 and one char in a string in the range of A-Z E.G. W and combine the two strings to make 2645237W. I can generate a random number no problem. What I'm stuck on is: 1. Generating a random Char as a string. 2. Combining the two strings to create one string. To be clear what it's for is a school assignment to achieve some extra credit in my marking. Like always I'm not looking for the full answer. Some pseudo-code or a working example would be fine but I'd like the final "A-HA!" moment to be my own doing. A final parameter. This end result (the one string) would need to be a generated 50 times differently (I can do this) and then used as a sort of password. (Meant to replicate a PPS number, the added char is the bit that has my whole class stumped).
I'm not looking to cheat my way to a coded answer, just stuck on this problem (We've all been there)
3 Answers 3
You can generate a random character simply by doing 'a' (or 'A' for upper case) and then generating a random number from 0 to 25 and adding that to it. i.e. 'a'+3 is 'd'. Note the use of a single quote character to say this is a char literal as opposed to the double quote for a String literal.
That random character can then be appended to the string. StringBuilder would do it for you easily, I'm not sure off hand what the String + operator will do with it.
7 Comments
int 65+14 gives 79, 'A'+14 gives letter 79. This is different from + in String which concatenates strings.Try,
Random rn = new Random();
int range = 9999999 - 1000000 + 1;
int randomNum = rn.nextInt(range) + 1000000; // For 7 digit number
System.out.println(randomNum);
Random rc = new Random();
char c = (char)(rc.nextInt(26) + 'A');
System.out.println(c);
String str = randomNum+""+c;
System.out.println(str);
str prints like 1757217Y
4 Comments
To generate the letter and append on your number sequence:
String msg1 = "random number sequence";
Random gen = new Random();
char c = (char) (65 + gen.nextInt(26));
StringBuilder sb = new StringBuilder();
sb.append(msg1);
sb.append(c);
String result = sb.toString();
System.out.println(result);
By the way, 65 is the ascii code of the letter 'A' and gen.nextInt(26) generates a number between 0 and 25, ie, we have a range between 65 and 90 which are the letters' A'-'Z' in ascii table
chardata type is actually represented by an integer. Find the integer range of the characters you want, generate a random int in that range, convert it to a char. From there turning an int and a char into strings and combining them should be easy.A, 66 =B, etc...