0

I am supposed to create a program that counts the number of specific types of characters entered by the user. The number of upper case letters, lower case letters, digits (0 through 9) and other characters other than the # sign are counted. The user enters # to exit.

import java.util.Scanner;
public class countchars
{
    public static void main (String args[])
    {
    Scanner input = new Scanner (System.in);

    char sym;
    int up = 0;
    int low = 0;
    int digit = 0;
    int other = 0;

    System.out.print("Enter a character # to quit: ");
    sym = input.next().charAt(0);

    while(sym != '#')
    {
    System.out.print("Enter a character # to quit: ");
    sym = input.next().charAt(0);

    if (sym >= 'a' && sym <= 'z')
        {
        low++;
        }   
    } 

    System.out.printf("Number of lowercase letters: %d\n", low);
    }
}

That's what I have so far for the lowercase count. The problem is when I run the program and enter 4 lowercase letters, it only counts 3.

3
  • you could try adding print statements inside your if statement together with your low++ to confirm how many times it entered the statement :) Commented Mar 7, 2013 at 6:29
  • Homework question? Should be tagged. Commented Mar 7, 2013 at 6:32
  • @EvanKnowles Home Work tag is OBSOLETE -> stackoverflow.com/tags/homework/info Commented Mar 7, 2013 at 6:37

3 Answers 3

4

You have called

input.next()

twice by the first time you count, so the first character is discarded, messing up your count by one.

Sign up to request clarification or add additional context in comments.

Comments

2

Change like this

while(sym != '#')
    {

    if (sym >= 'a' && sym <= 'z')
        {
        low++;
        }

    System.out.print("Enter a character # to quit: ");
    sym = input.next().charAt(0);

    }

Comments

0

don't use two times input.next();

use this

sym = input.next().charAt(0);

    while(sym != '#')
    {
    System.out.print("Enter a character # to quit: ");
    //sym = input.next().charAt(0); removed this line and try

    if (sym >= 'a' && sym <= 'z')
        {
        low++;
        }


    } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.