Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop only loop 1 time JAVA?

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);

}
like image 393
cchua Avatar asked Jul 21 '26 02:07

cchua


1 Answers

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.

like image 187
Stephen C Avatar answered Jul 23 '26 15:07

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!