简体   繁体   中英

Why Does Java Skip My If Statement in a While Loop?

I'm trying to construct a program that counts the amount of vowels in a given string. Everything seems to run fine until I get to the while loop. It completely skips my if statement and goes straight to the incrementation of integer r. I feel that this is a syntax error; however, I can't imagine what it could be. Any thoughts?

String e [] = {"a", "e", "i", "o", "u"};
String a = "banana";
int r = 0;
int b = 0;
int c = 1;
int z = 0;
String q = " ";
for(int i = 0; i < a.length(); i++) {
    q = a.substring(b, c);
    b++;
    c++;
    while(r < e.length) {
        if(q.equalsIgnoreCase(e[r])){
            z = z + 1;
        }
        r++;
    }   
}
System.out.println(z);

First things first, you either need to reset r back to zero either before the while loop or after.

Next simplifying the code. If you're wanting to know how many vowels are in a String , you can use String.replaceAll(String regex, String replacement) to remove all non-vowel letters from the String then the length of the String will equal how many vowels you have.

public static void main(String[] args) {
    String a = "banana";
    System.out.println(a.replaceAll("[^aeiouAEIOU]", "").length());
}

Result:

3

The regex pattern, in the replaceAll() , means to match any character that is not a lower/upper case vowel ( Regex Pattern Reference ) and replace it with and empty string (remove it). The result is a new String with nothing but vowels in it.

If regex is too complicating to understand, then walk the String like you're already doing, but check if each character is a vowel like this:

public static void main(String[] args) {
    String vowels = "aeiouAEIOU";
    String a = "banana";

    int vowelCount = 0;
    for (int i = 0; i < a.length(); i++) {
        String letter = Character.toString(a.charAt(i));
        if (vowels.contains(letter)) {
            vowelCount++;
        }
    }

    System.out.println(vowelCount);
}

You don't need to use String.substring() to extract a single character, that's what String.charAt() is for. Also, instead of having an array of vowels, have a String of vowels so you can use String.contains() to see if the letter is a vowel.

As you can see, there are many ways to construct an algorithm to solve this problem. Choose what makes best sense to you and helps you learn.

try it like this

    String e [ ] = {"a", "e", "i", "o", "u"};
    String a = "banana";
    int r = 0;
    int b = 0;
    int c = 1;
    int z = 0;
    String q = " ";
    for(int i = 0; i < a.length(); i++){
        q = a.substring(b, c);
        b++;
        c++;
        r=0;
        while(r < e.length() ){
            if(q.equalsIgnoreCase(e [r])){
                z = z + 1;

            }
            r++;
        }

    }
    System.out.println(z);

I set r to 0 each time, I removed a comma after "u", and I added parenthesis after a.length, and I removed -1 after a.length()

Setting r to 0 is necessary because r represents which of the vowels you are testing for. So for each of the letters in the word, you are testing each of the vowels. So after testing each letter (of banana) you have to set r to 0 so that it will start checking at "a" again (then e then i ...). Then it moves on to the next letter in banana, so it needs to go back to "a" again.

And using e.length() instead of length() -1 is needed because otherwise it will never be testing for "u" . It just happens to work because banana has no "u"'s

You need to reset r = 0 in your for loop.

for (int i = 0; i < a.length(); i++) {
    q = a.substring(b, c);
    b++;
    c++;
    r = 0;
    while (r < e.length - 1) {
        if (q.equalsIgnoreCase(e[r])) {
            z = z + 1;
        }
        r++;
    }
}

If you do not reset r to 0 then you will end up value of r to 4 when first time for loop executes (for character b ). So when next time your for loop executes, value of r is 4 so every time it will check this condition while (4 < e.length - 1) which will result in false and it won't enter into while loop. So in case of banana , it will execute while for b but not for remaining characters anana .

If you are using any IDE then you can debug your code and see how values are changing.

For Eclipse : Debugging With Eclipse

Firstly format the code when you are sharing as a help to others. Below is the running code. You should have run it and fixed the comma added to the array e. Just resetting the r index fixes it.

Here is a JDK 8 version

import java.util.*;

class Tester{
  public static void main(String args[]){
    String vowels [ ] = {"a", "e", "i", "o", "u"};
    String word = "bananae";

    int vowelCount = 0;
    Object[] vowelsInTheWord = Arrays.stream(vowels).filter(l -> word.indexOf(l) > -1).toArray();
    System.out.println(vowelsInTheWord.length);
  }
}

and your version fixed

class Tester{
  public static void main(String args[]){
    String e [ ] = {"a", "e", "i", "o", "u"};
    String a = "banana";
    int r = 0;
    int b = 0;
    int c = 1;
    int z = 0;
    String q = " ";
    for(int i = 0; i < a.length(); i++){
      q = a.substring(b, c);
      b++;
      c++;

      r = 0;

      while(r < e.length){
        if(q.equalsIgnoreCase(e [r])){
           z = z + 1;
        }
        r++;
      }
    }
    System.out.println(z);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM