gpt4 book ai didi

java - 交换两个数组中的两个字符

转载 作者:行者123 更新时间:2023-12-01 06:32:49 25 4
gpt4 key购买 nike

所以我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com