Home > OS >  Java 'error: class expected' when usig array length method
Java 'error: class expected' when usig array length method

Time:12-09

I am doing an assignment for my Java class that requires me to write a program that displays the number of uppercase letters in a string. I am getting the error on my line 26 (for (int i = 0; i < ch[].length; i ){) any help would be appreciated.

import java.util.Scanner;

public class Uppercase{
    public static void main(String[] args){
        char[] newWord;
        Scanner userWord = new Scanner(System.in);
        System.out.println("Enter a word");
        
        String word = userWord.nextLine();
        
        System.out.println("There are "   newWord.numUppercase(word)   "uppercase letters");
    }
    
    public int numUppercase(String s){
        char[] ch = new char[s.length()];
        
        for (int i = 0; i < s.length(); i  ){
            ch[i] = s.charAt(i);
            
        int uppercase = 0;
        for (int i = 0; i < ch[].length; i  ){
            if(ch[i].valueOf() > 64 && ch[i].valueOf() < 91){
                uppercase  ;
            }
        }
        return uppercase;
        }
    }
}

CodePudding user response:

Your bug-fixed class:

public class Uppercase{
public static void main(String[] args){
    Scanner userWord = new Scanner(System.in);
    System.out.println("Enter a word");

    String word = userWord.nextLine();

    System.out.println("There are "   numUppercase(word)   "uppercase letters");
}

public static int numUppercase(String s){
    char[] ch = new char[s.length()];

    for (int i = 0; i < s.length(); i  ){
        ch[i] = s.charAt(i);

        int uppercase = 0;
        for (int j = 0; j < ch.length; j  ){
            if(ch[j] > 64 && ch[j] < 91){
                uppercase  ;
            }
        }
        return uppercase;
    }
    return 0;
}}

CodePudding user response:

Aside from the typo, the calculation of the uppercase letters is incorrect.

First, there's no need to create ch array, copy the characters from the input string, and then check the chars in ch array.

Second, an assumption that the uppercase letters reside in the range [65, 90] is applicable only to English letters. There are several Character::isUpperCase methods to check if a character or a Unicode codepoint is upper case. Character::isUpperCase(char c) has been existing for a while since Java 1.0.

So, that being said, an example counting uppercase letters could be as follows:

public static int numUpperCase(String s) {
    int num = 0;
    if (s != null) {
        for (char c : s.toCharArray()) {
            if (Character.isUpperCase(c)) num  ;
        }
    }
    return num;
}

A oneliner using Stream API:

static int numUpperCase(String str) {
    return Optional.ofNullable(str)
           .map(s -> (int) s.chars().filter(Character::isUpperCase).count())
           .orElse(0); // if input string is null
}
  • Related