Search code examples
javamethodscountpunctuation

How to count punctuation marks in a String in java?


I need to write a program to count certain punctuation marks in a string. I have this code I thought would work, but at every charAt, i have an error that says the left hand of the assignment must be a variable. Need help fixing this

public static void main(String[] args)
{
    Scanner kbd = new Scanner (System.in);

    System.out.println("Enter a string: ");
    String s = kbd.next();

    countPunctuation(s);
}
public static int countPunctuation(String s)
{
    int periodCount = 0;
    int commaCount = 0;
    int semicolonCount = 0;
    int colonCount = 0;
    int exclamationCount = 0;
    int questionCount = 0;
    int total = 0;


    for(int i = 0; i < s.length(); i++)
    {
        if(s.charAt(i) = ".")
        {
            periodCount++;
            total++;
        }
        if(s.charAt(i) = ",")
        {
            commaCount++;
            total++;
        }
        if(s.charAt(i) = ";")
        {
            semicolonCount++;
            total++;
        }
        if(s.charAt(i) = ":")
        {
            colonCount++;
            total++;
        }
        if(s.charAt(i) = "!")
        {
            exclamationCount++;
            total++;
        }
        if(s.charAt(i) = "?")
        {
            questionCount++;
            total++;
        }

    }

    System.out.println("There are " + periodCount + " periods in this String.");
    System.out.println("There are " + commaCount + " commas in this String.");
    System.out.println("There are " + semicolonCount + " semicolons in this String.");
    System.out.println("There are " + colonCount + " colons in this String.");
    System.out.println("There are " + exclamationCount + " exclamation marks in this String.");
    System.out.println("There are " + questionCount + " quesiton marks in this String.");


    return total;
}

Solution

  • Equality check is with == not with =. You need to have something like if(s.charAt(i) == '.') or you can use switch for this case:

    for(int i = 0; i < s.length(); i++) {
        switch(s.charAt(i)) { 
         case '.':
            periodCount++;
            break;
         case ',':
            commaCount++;
            break;
         ... // similar conditions for others
        }
        total += 1;
    }