1

The following code creates a string array 'one' as [c, a, t, a, n, d, d, o, g]. Now I want to create an int array 'two' in which place of every 'a' is 3 and all other places are filled by 5 forming

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

but the code is giving every element equal to 5, so it prints as

5 5 5 5 5 5 5 5 5 :

The code I used starts here:

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]+" ");

          }

        }
   }

Being new to programming and java I need help to rectify this code to get the required output:

5  3  5  3  5  5  5  5  5
MilapTank
  • 9,988
  • 7
  • 38
  • 53
Soon
  • 339
  • 2
  • 10
  • With `split("(?!^)"` you seem to want to split your string to array of strings with single characters. If that is the case then you can avoid negative-look-ahead by [upgrading your JVM to Java8 and using `split("")`](http://stackoverflow.com/q/22718744/1393766). You can also use `toCharArray()` to create array of characters `char[]` which would let you compare characters like you did in your code but you would need to use `'` instead of `"` since `"` means start/end of string and `'` represents start/end of character. So you could use code like `if(one[j]=='a'){` – Pshemo Jun 11 '14 at 13:27

2 Answers2

6

You are using == not .equals() to compare strings.

Use one[j].equals("a").

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • 1
    After so many years...still `==equals` bringing lots of votes... :) Can't Stop MySelf +1. – akash Jun 11 '14 at 12:53
  • Great TAsk, your answer has rectified my code and it is working according to my need. – Soon Jun 11 '14 at 13:02
2

You use == when comparing primitives, like int, double, char, etc.

When comparing objects, one has to use the equals() method, which is a method that every object inherits from the Object class.

This is from the javadocs:

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

Since String is an object, and not a primitive, one must use the equals method to check for equality between two String objects.

Arash Saidi
  • 2,228
  • 20
  • 36