javamethodsreturncharat

method to return false - conditional


I have constructed the below method, but I need the method to return as false, if the ID length is not 7 characters long.

I believe I need to define the length somewhere in here as 7 (but I could be wrong in my understanding here) and I think I might be missing a return statement?

Any ideas?

 public void validIdd()
 {
 int nameLenght = id.length();
for(int i = 0; i < nameLenght ; i++) {
    char character = id.charAt(i);
    int ascii = (int) character; 
    int ch = ascii % 10; 
    int total = ch;
}

Solution

  • First change the return type to boolean and pass the id as a parameter. Check if the id has a length of 7.

    public boolean validIdd(String id)
     {
     int nameLenght = id.length();
     if(nameLength != 7) return false;
     for(int i = 0; i < nameLenght ; i++) {
        char character = id.charAt(i);
        int ascii = (int) character; 
        int ch = ascii % 10; 
        int total = ch;
     }
     return true;
    }
    

    If you want to return the total variable you have to set the return type to int and if the length is less than 7 you have to return either null or a value which can not be created like for example -1