I have 2 chars I need converting to a string. I can convert one no problem but how do I turn 2 randomly generated chars into one string? Here is my code so far, the aim of my program is to generate two chars at random and return them:
import java.util.Random; public class PasswordGenerator { Random rand = new Random(); public String uppercaseLetters() { char char1; char char2; String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String result; char1 = alphabet.charAt(rand.nextInt(25)); char2 = alphabet.charAt(rand.nextInt(25)); result = String.valueOf(char1, char2); return result; } public static void main(String[] args) { PasswordGenerator pg = new PasswordGenerator(); System.out.println(pg.uppercaseLetters()); } }
Advertisement
Answer
A String
concatenated with a char
is a String
1. So you could do,
result = String.valueOf(char1) + char2;
or something like
result = "" + char1 + char2;
Also, I’d really prefer to use a StringBuilder
. I’d also make the length
an argument, move the Random
and String
out of the method.
class PasswordGenerator { final Random rand = new Random(); final static String upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public String uppercaseLetters(int len) { StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append(upperCase.charAt(rand.nextInt(upperCase.length()))); } return sb.toString(); } }
Then you could call it like pg.uppercaseLetters(2)
or pg.uppercaseLetters(4)
and get n
letters (instead of 2
).
1char
is an integral value in Java, so char
+char
is an int
.