How to check if a char is upper/lowercase?

Viewed 876

The following code is supposed to convert letters to numbers and give the sum, but ignore any letters that are uppercase.

Example:

The input abcde should return 15. The input abCde should return 12.

Any help is appreciated.

static int strScore(String str[], String s, int n) { 
    int score = 0, index=0; 

    for (int i = 0; i < n; i++) { 
        if (str[i] == s) { 

        for (int j = 0; j < s.length(); j++) 
            score += s.charAt(j) - 'a' + 1; 
            index = i + 1; 
            break; 
        } 
    } 

    score = score * index; 
    return score; 
} 

public static void main(String[] args) {        
    String str[] = { "abcde" };
    String s = "abcde"; 

    int n = str.length; 
    int score = strScore(str, s, n); 
    System.out.println( score); 
}
3 Answers

Use Character.isLowerCase(...).

So this is what your strScore method should look like:

static int strScore(String str[], String s, int n) { 
    int score = 0, index = 0; 
    for (int i = 0; i < n; i++) { 
        if (str[i].equals(s)) { 
            for (int j = 0; j < s.length(); j++) {
                char c = s.charAt(j);
                if(Character.isLowerCase(c)) // <-- This is the important part
                    score += c - 'a' + 1;
            }
            index = i + 1; 
            break; 
        } 
    }

    score = score * index; 
    return score; 
}

As pointed out in the comments, there is no need for the str and therfore neither the n parameter. This is a better version:

static int strScore(String s) { 
    int score = 0;

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if(Character.isLowerCase(c))
            score += c - 'a' + 1;
    }

    return score; 
}

There are two things to address:

  1. You have used == to compare strings. You need to use .equals
  2. You need to put a check like if(s.charAt(j)>= 'a' && s.charAt(j)<'z')
for (int i = 0; i < n; i++) { 
    if (str[i].equals(s)) { 
        for (int j = 0; j < s.length(); j++) 
            if(s.charAt(j)>= 'a' && s.charAt(j)<'z') {
                score += s.charAt(j) - 'a' + 1; 

You can avoid passing String str[] = { "abcde" }; which has one element which equals s to The method. You can also avoid passing n which is an simply str.length():

static int strScore(String s) {
    int score = 0, index = 0;
    for (int i = 0; i < s.length(); i++) {
        for (char c : s.toCharArray()) { 
            if(c >= 'a' && c <'z') {     //alternatively if(Character.isLowerCase(c))
                score += c - 'a' + 1;
            }
        }
        index = i + 1;
        break;
    }
    score = score * index;
    return score;
}
Related