3

I have a trouble with the for loop method that only loop 1 times whats is the problem? In the array was no problem at all, it able to print the value I want to.

here is my code:

public static void main(String[] args){

        String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
        String[] word = s.split(",");
        StringBuffer str = new StringBuffer();
        Integer total = 0;

        for (int y = 0; y < word.length; y++){
            if(word[y].toString().equals("Apple2") ){
                total++;
                //str.append(word[y].toString());
            }else if(word[y].toString().equals("Apple3") ){
                total++;
                //str.append(word[y].toString());
            }else if(word[y].toString().equals("Apple4") ){
                total++;
                //str.append(word[y].toString());
            }
            else if(word[y].toString().equals("Apple1") ){
                total++;
                //str.append(word[y].toString());
            }


    }
        System.out.println( word[0] + word[1] + word[2] +  word[3] + word[4] + word.length);
        System.out.println(str + "hihi" + total);

}
2
  • 3
    Why are you calling .toString() on an object which is already a string? Commented Feb 25, 2013 at 3:24
  • that my mistake, but i remove it the loop still loop 1 times? any solution Commented Feb 25, 2013 at 3:26

5 Answers 5

5

The others have nailed the cause of your problem. However, the fix they suggest is rather too specific ... and fragile. (Splitting with split("\\s*,\\s*") is better but it won't cope with whitespace at the start / end of the entire string.)

I suggest that you continue to use split(","), but trim the words before testing; e.g.

  for (int y = 0; y < word.length; y++) {
        String trimmed = word[y].trim();
        if (trimmed.equals("Apple2")) {
            total++;
            //str.append(trimmed.toString());
        } else if (trimmed.equals("Apple3")) {
            // etcetera

or better still:

  String[] words = s.split(",");
  for (String word : words) {
        String trimmed = word.trim();
        if (trimmed.equals("Apple2")) {
            total++;
            //str.append(trimmed.toString());
        } else if (trimmed.equals("Apple3")) {
            // etcetera

That will make your code work irrespective of the whitespace characters around the commas and at the start and end of the string. Robustness is good, especially if it costs next to nothing to implement.

Finally, you could even replace the if / else if / ... stuff with a Java 7 String switch statement.

Sign up to request clarification or add additional context in comments.

Comments

3

Try splitting on ", " (with space)

String[] word = s.split(", ");

without that space in split word[1] would look like " Apple1" instead "Apple1"


Other option would be calling word[y].trim().equals("Apple2") to get rid of that additional space, but I would say including it in split is better. If you aren't sure how many white-spaces can be near comma you can split this way split("\\s*,\\s*") to include all white-spaces around comma.


Also as Matt Ball pointed in his comment you don't need to call toString() on word[y] since it is already String.

2 Comments

+1 - In fact, there is nothing wrong with the for loop. It is the code in the loop body that is broken ... 'cos it is not taking account of leading / trailing spaces in the words.
Indeed. Adding System.out.println("Iterating with y="+y); immediately after the for makes it clear that the loop iterates, but does nothing unless word[y] has one of the expected values.
2

you ignore the space during split. String[] word = s.split(", ");

Comments

1

You'are split by "," but your String contains ", ". You can change the s.split(","); to s.split(", ");

Or trim the split's result like this :

public static void main(String[] args) {

        String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
        String[] word = s.split(",");
        StringBuffer str = new StringBuffer();
        Integer total = 0;
        for (int y = 0; y < word.length; y++) {
            if (word[y].trim().equals("Apple2")) {
                total++;
                // str.append(word[y].toString());
            } else if (word[y].trim().equals("Apple3")) {
                total++;
                // str.append(word[y].toString());
            } else if (word[y].trim().equals("Apple4")) {
                total++;
                // str.append(word[y].toString());
            } else if (word[y].trim().equals("Apple1")) {
                total++;
                // str.append(word[y].toString());
            }

        }
        System.out.println(word[0] + word[1] + word[2] + word[3] + word[4]
                + word.length);
        System.out.println(str + "hihi" + total);

    }

Comments

0

There is nothing wrong with your code but the problem lies in the String that you are giving to the variable.

String s = "Apple0, Apple1, Apple2, Apple3, Apple4";

Here the string contains spaces between them after the comma. So that when you split your string it splits like

word[0]= "Apple0"
word[1]= " Apple1"
word[2]= " Apple2"
word[3]= " Apple3"

and so on.

So that when you compare like

word[y].equals("Apple1") it returns false because " Apple1" and "Apple1" are two different strings. So that initialize your string like this

String s = "Apple0,Apple1,Apple2,Apple3,Apple4"; // without white spaces

It will work fine. Or you can use trim method in your existing code without changing String like

word[y].trim().equals("Apple1") //It will trim all the leading and trailing white spaces.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.