所以我有 2 个字符数组和两个随机数,每个数组一个数字。
我想获取第一个数组中随机数位置的字符,并将其与第二个数组中第二个随机数位置的字符交换。我试过这个:
char[] chs1 = {'h', 'e', 'l', 'l', 'o'};
char[] chs2 = {'w', 'o', 'r', 'l', 'd'};
Random rand = new Random();
int ranNum1 = rand.nextInt(chs1.length);
int ranNum2 = rand.nextInt(chs2.length);
chs1[ranNum1] = chs2[ranNum2];
chs2[ranNum2] = chs1[ranNum1];
有谁知道怎么做吗?
最佳答案
您需要一个临时变量来交换:
char temp = chs1[ranNum1];
chs1[ranNum1] = chs2[ranNum2];
chs2[ranNum2] = temp;
关于java - 交换两个数组中的两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16708137/