Search code examples
javaloops

Count input without spaces, commas, or periods - Java


Input is "Listen, Mr. Jones, calm down."


import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      String userText;
      int numPun = 0; //number of punctiation and spaces
      // Add more variables as needed
   
      userText = scnr.nextLine();  // Gets entire line, including spaces. 

     for (int i = 0; i < userText.length(); i++){
        if ((userText.charAt(i) != ' ') && (userText.charAt(i) != ',') && (userText.charAt(i) != '.'));{
           numPun++;
        }
     }
     System.out.println(numPun);
   }
}

My current output is to 29, which is the total amount of characters in the whole line. Expected output is supposed to be 21. Where am i going wrong here?


Solution

  • Stray semicolon terminating if, and use && NOT ||

    In a previous version of this answer I specified to use || instead of &&. DO NOT do that. Kudos to Basil Bourque's answer for being the first one to point that out.

    Use:

    for (int i = 0; i < userText.length(); i++){
        char current = userText.charAt(i);
        if (current  != ' ' && current  != ',' && current  != '.'){
           numPun++;
        }
     }
    

    You have an extra ; after the if statement expression.

    See it in action

    Explanation:

    In the previous version of this answer the expression current != ' ' || current != ',' || current != '.' is equal to if current is not a space or is not a comma or is not a period do this:.

    That meant that if the character was a comma, it would add 1 to numPun, because it was not a space.

    In the new expression, it is equal to if current is not a space and is not a comma and is not a period. Therefore it would first check whether it was a space, then a comma, then a period.