public class Random {
public static void main(String[] args) {
char cs[] = new char[5];
for (int i = 0; i < cs.length; i++) {
while (true) {
char c = (char) (Math.random() * 125);
if (Character.isLetter(c) || Character.isDigit(c)) {
cs[i] = c;
break;
}
}
}
String result = new String(cs);
// String result=String.valueof(cs);//正確
//String result=cs.toString();//錯誤
System.out.println(result);
}
最後附上new string、string.valueof、toString與(string)的區別: