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



下面的代码创建一个字符串数组'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

您正在使用==而不是.equals()来比较字符串。

使用one[j].equals("a")

在比较原语时使用==,如int, double, char

在比较对象时,必须使用equals()方法,该方法是每个对象从object类继承的方法。

这是来自javadocs:

boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.

由于String是一个对象,而不是一个原语,因此必须使用equals方法来检查两个String对象之间是否相等。

最新更新