由特定姓和一组字符串随机生成一串姓名,按照习惯总字数最多4个,为什么我输出的除了两位数的名字就是数字啊

由特定姓和一组字符串随机生成一串姓名,按照习惯总字数最多4个,为什么我输出的除了两位数的名字就是数字啊


```java
import java.io.UnsupportedEncodingException;
import java.util.Random;
     
public class ChineseName {
     
    public static void main(String[] args) {
            Random random=new Random(System.currentTimeMillis());
            String[] Surname= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨"};
            
            int index=random.nextInt(Surname.length-1);        
            String name = Surname[index]; //获得一个随机的姓氏
            int a=(int)(Math.random()*3+1);
            if(a==3){
                name+=getChinese()+getChinese()+getChinese();
            }else if(a==2){
                name+=getChinese()+getChinese();
            }
            else {
                name+=getChinese();
            }
            System.out.println(name);
        }
        
        public static char getChinese() {
            String str = "特指汉族的语言文字即汉语和汉字在汉字文化圈和海外华人社区中中文也被称为华文汉文";
            Random random = new Random();

            int index = random.nextInt(str.length());

            return str.charAt(index);
     
    }
}


![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/92523222407610.png "#left")

getChinese() 返回的是char 类型, 后面 几个char 相加,是算的 字符对应的整形值, 加上 空字符拼接一下 "" +

改成这个:

        if(a==3){
            name+="" + getChinese()+getChinese()+getChinese();
        }else if(a==2){
            name+="" + getChinese()+getChinese();
        }
        else {
            name+=getChinese();
        }


或者 你 getChinese() 返回 String 吧

img


如有帮助,欢迎采纳哈!

当随机值a为2或者3的时候会出问题,因为你这里 name+=getChinese()+getChinese()+getChinese();
他是优先计算 getChinese()+getChinese()+getChinese();的,而你的返回类型是char,char相加直接变成int值了,然后string又拼上了这些数字