gpt4 book ai didi

java - 使int数组与java字符串数组并行

转载 作者:行者123 更新时间:2023-11-29 10:13:49 24 4
gpt4 key购买 nike

<分区>

以下代码创建一个字符串数组 'one' 作为 [c, a, t, a, n, d, d, o, g]。现在我想创建一个 int 数组 'two',其中每个 'a' 的位置都是 3,所有其他位置都由 5 组成

int two= {5, 3, 5, 3, 5, 5, 5, 5, 5}

但是代码给出的每个元素都等于 5,所以它打印为

5 5 5 5 5 5 5 5 5 :

我使用的代码从这里开始:

import com.google.common.collect.ObjectArrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;

public class StringInt {


public static void main(String[] args) {

String str= "cat and dog";
String[] word = str.split("\\s");
String[] one = new String[0];
for(int i=0; i<word.length; i++){
one = ArrayUtils.addAll(one, word[i].split("(?!^)"));
}

System.out.println("One : " + Arrays.toString(one));

int[] b = new int[one.length];

for(int j=0; j<one.length; j++){
if(one[j]=="a"){
b[j]=3;
} else {
b[j]=5;
}
System.out.print(b[j]+" ");

}

}
}

作为编程和 java 的新手,我需要帮助来纠正此代码以获得所需的输出:

5  3  5  3  5  5  5  5  5

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