0

I'm working on a Login system in Java and am currently focusing on eMail verification. I'm trying to verify that emails only contain one "@".

To do this I've made a function to return the number of chars in a string:

    public static int numberOfCharsInString(String inputString, Character inputChar) {

        char[] stringToCharArray = inputString.toCharArray();

        int number = 0;

        for (int i = 0; i == inputString.length(); i++) {
            if (stringToCharArray[i] == (inputChar)) {
                number++;
            }
        }
        return number;
    }

There are no compilation errors and the function only returns zero. Any help would be much appreciated.

Cameron Cheung
  • 197
  • 1
  • 2
  • 12
  • 2
    You need `i <`, not `i ==`. You could have put a print in the loop and would have noticed that the loop never runs. The loop runs while the condition is true, but you're using it as though the loop stops when the condition is true. – Carcigenicate May 21 '19 at 12:19
  • 1
    Check https://stackoverflow.com/questions/624581/what-is-the-best-java-email-address-validation-method – George Z. May 21 '19 at 12:20
  • 2
    `i == inputString.length()` -> `i < inputString.length()` since this condition decides if loop should iterate, but at start `i=0` which is not equal to `inputString.length()`. – Pshemo May 21 '19 at 12:24

1 Answers1

1

Please try below code, it will work

public static int numberOfCharsInString(String inputString, Character inputChar) {
    int number = 0;
    for (int i = 0; i < inputString.length(); i++) {
        if (inputString.charAt(i) == inputChar)
            number++;
    }
    return number;
}
Chirag Shah
  • 353
  • 1
  • 13