java随机生成10个字母A到Z。要求不重复!新手谢谢

如题所述

public class Egg{
    public static void main(String[] args){
        String word = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String tmp = "";
        for(int i = 0; i < 10; i++){
            int rand = (int)(Math.random() * word.length());
            char c = word.charAt(rand);
            if(!tmp.contains(c+"")){
                tmp += c;
            }else{
                i--;
            }
        }
        System.out.println(tmp);
    }
}

追问

用random直接随机出字母,然后怎么判断。

追答

定义一个存储结果的字符串,
如果字符串不存在每次随机生成的字符,就累加

如果存在,就返回,重新随机

追问

没懂

追答//方法2
public class Egg{
    public static void main(String[] args){
        String tmp = "";
        for(int i = 0; i < 10; i++){
            int rand = (int)(Math.random() * (91 - 65)) + 65;
            String c = (char)rand + "";
            if(tmp.indexOf(c) == -1){
                tmp += c;
            }else{
                i--;
            }
        }
        System.out.println(tmp);
    }
}

温馨提示:答案为网友推荐,仅供参考