12

yo, so im trying to make a program that can take string input from the user for instance: "ONCE UPON a time" and then report back how many upper and lowercase letters the string contains:

output example: the string has 8 uppercase letters the string has 5 lowercase letters, and im supposed to use string class not arrays, any tips on how to get started on this one? thanks in advance, here is what I have done so far :D!

import java.util.Scanner;
public class q36{
    public static void main(String args[]){

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Give a string ");
        String input=keyboard.nextLine();

        int lengde = input.length();
        System.out.println("String: " + input + "\t " + "lengde:"+ lengde);

        for(int i=0; i<lengde;i++) {
            if(Character.isUpperCase(CharAt(i))){

            }
        }
    }
}
eckes
  • 10,103
  • 1
  • 59
  • 71
yyzzer1234
  • 153
  • 1
  • 1
  • 7
  • 2
    In the future and also right now, you'll get better help if you show your attempt to solve it first. If you don't do this, how will we know where you're stuck or what confuses you? Also your showing your effort gains much in terms of respect for you and your question, showing that you're willing to put in the effort and initiative to try to solve it yourself first. Besides, what do you have to lose by trying and showing us the effort? – Hovercraft Full Of Eels Aug 10 '14 at 02:28
  • its basically the whole thing I dont understand, Im able to understand the question and thats about it, no idea how to get started, if I knew I would, but I mean the only thing I would be able to do here is import java.util.Scanner; and that basic stuff I bascailly use/do for every single prgram – yyzzer1234 Aug 10 '14 at 02:30
  • Often times the best way for you to do this, and also the best way for you to complete your project is to try to "divide and conquer", to break your big problem into its small constituent steps, and then try to solve each small step one at a time. If a step is especially difficult, then try to subdivide it, and try to solve it in isolation from your big program. So here your steps can include 1) reading in the String, 2) creating your upper and lower case count int variables, 3) iterating through the chars of the String, 4) check if the char is upper or lower case, 5) incr the appropr var... – Hovercraft Full Of Eels Aug 10 '14 at 02:31
  • So do this -- divide and conquer, and then if still stuck, show what you've got and ask your **specific** question, something you've yet to do. – Hovercraft Full Of Eels Aug 10 '14 at 02:32
  • ok my specific question is how do I actually count upper and lower case letters in a string? rest of it I should be able to do Im sure, I guess on 2) I just make make two int variables for upper and lowercase (one for each) and set them equal to 0? idk what you mean on 3) :/ – yyzzer1234 Aug 10 '14 at 02:34
  • 1
    As noted above. Also note that the Character class has an `Character.isUpperCase(char ch)` static method as well as a `Character.isLowerCase(char ch)` static method that can help you out. – Hovercraft Full Of Eels Aug 10 '14 at 02:35
  • ahh ok cool, thanks a lot, what does the ch mean? – yyzzer1234 Aug 10 '14 at 02:37
  • That's just a dummy name for the char parameter. – Hovercraft Full Of Eels Aug 10 '14 at 02:37
  • hmm ok, so do I have to use .CharAt or something? and if yes, how do i use it? srry, I have no clue on char and stuff :( – yyzzer1234 Aug 10 '14 at 02:42
  • 3
    Don't ask -- try! You've got a computer programming laboratory at your fingertips, so use it. Experiment, play, write code, run it, change it, push it to the limit and then go beyond, find out what works what doesn't work. Trust me, you're not going to blow up your computer, you're not going to bring on doom and damnation from the effort. Don't ask us here -- find out for yourself. That's what learning and what programming is all about! – Hovercraft Full Of Eels Aug 10 '14 at 02:44
  • :( ok can you help me if I ctrl c ctrl v the code I got so far in the question? – yyzzer1234 Aug 10 '14 at 02:47
  • 3
    Yes, questions should have code that you've tried and research that you've done. – jdphenix Aug 10 '14 at 02:50
  • I think maybe if I make two variables int upperCase, lowerCase =0 and use if statement in a for loop and just upperCase++ and then make the same thing for lowerCase with else? lowerCase++; ?? idk how to make the for loop, if loop* with all these char methiods, very confusing :( – yyzzer1234 Aug 10 '14 at 02:55
  • Sorry, I had the wrong link to the Character class. Let me try this again: [Character](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html), [String](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) – TNT Aug 10 '14 at 02:58
  • 1
    Hint: There is nothing called `CharAt`. If you look at the documentation for String (which you should have done before starting this endeavor) you will see that there *is* an *instance* method called `charAt`. *Instance method* means that it must be qualified by an "instance" -- an object of the class. (In this case the class is, of course, `String`, and you have an object of that class in your code.) – Hot Licks Aug 10 '14 at 03:04
  • ahh ok, I changed it out with if(Character.isUpperCase(char input){ upperCase++; but i get Error: '.class' expected – yyzzer1234 Aug 10 '14 at 03:07

8 Answers8

23

Simply create counters that increment when a lowercase or uppercase letter is found, like so:

for (int k = 0; k < input.length(); k++) {
    /**
     * The methods isUpperCase(char ch) and isLowerCase(char ch) of the Character
     * class are static so we use the Class.method() format; the charAt(int index)
     * method of the String class is an instance method, so the instance, which,
     * in this case, is the variable `input`, needs to be used to call the method.
     **/
    // Check for uppercase letters.
    if (Character.isUpperCase(input.charAt(k))) upperCase++;

    // Check for lowercase letters.
    if (Character.isLowerCase(input.charAt(k))) lowerCase++;
}

System.out.printf("There are %d uppercase letters and %d lowercase letters.",upperCase,lowerCase);
TNT
  • 2,900
  • 3
  • 23
  • 34
  • THANKS a lot, it worked, I got confused for a bit when this other guy was saying stuff about charAt() :D, if he didnt lead me in the wrong direction I think I would have made it myself! I was so close! thanks a lot man! :) actually had input.charAt at first, but replaced it with the other stuff as you can see in the question, since i was extremely unsure on how to use it!!! – yyzzer1234 Aug 10 '14 at 03:16
  • I see `Character.isUpperCase / isLowerCase` are rather slow. In case of just Latin `(c>='A' && c<='Z')` and `(c>='a' && c<='z')` give better performance. – kio21 Mar 31 '23 at 10:25
6

java 8

private static long countUpperCase(String inputString) {
        return inputString.chars().filter((s)->Character.isUpperCase(s)).count();
    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }
Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104
5

The solution in Java8:

private static long countUpperCase(String s) {
    return s.codePoints().filter(c-> c>='A' && c<='Z').count();
}

private static long countLowerCase(String s) {
    return s.codePoints().filter(c-> c>='a' && c<='z').count();
}
Rodolfo Martins
  • 131
  • 1
  • 4
1

You can try the following code :

public class ASCII_Demo
{
    public static void main(String[] args)
    {
        String str = "ONCE UPON a time";
        char ch;
        int uppercase=0,lowercase=0;
        for(int i=0;i<str.length();i++)
        {
            ch = str.charAt(i);
            int asciivalue = (int)ch;
            if(asciivalue >=65 && asciivalue <=90){
                uppercase++;
            }
            else if(asciivalue >=97 && asciivalue <=122){
                lowercase++;
            }
        }
        System.out.println("No of lowercase letter : " + lowercase);
        System.out.println("No of uppercase letter : " + uppercase);
    }
}
Aditya
  • 1,214
  • 7
  • 19
  • 29
  • 1
    The term "ASCII value" is a bit missleading, you actually convert it to the unicode code unit. And restricting yourself to only ASCII codeset is a thing you should avoid when you can use the power of Java's character classification which is internationalized. – eckes Aug 10 '14 at 04:24
1

Use regular expressions:

public Counts count(String str) {
    Counts counts = new Counts();
    counts.setUpperCases(str.split("(?=[A-Z])").length - 1));
    counts.setLowerCases(str.split("(?=[a-z])").length - 1));
    return counts;
}
CMR
  • 986
  • 7
  • 16
0
import java.io.*;
import java.util.*;
public class CandidateCode {
    public static void main(String args[] ) throws Exception {
         int count=0,count2=0,i;
        Scanner sc = new Scanner(System.in);
         String s = sc.nextLine();
         int n = s.length();
         for( i=0; i<n;i++){
             if(Character.isUpperCase(s.charAt(i)))
                 count++;
             if(Character.isLowerCase(s.charAt(i))) 
             count2++;
         }
             System.out.println(count);
             System.out.println(count2);
         }



}
0

You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, please try to import the least number of libraries. So, avoid using .* as much as you can.

import java.util.Scanner;

public class q36 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Give a string ");
        String input = keyboard.nextLine();
        int numberOfUppercaseLetters =
                Long.valueOf(input.chars().filter(c -> Character.isUpperCase(c)).count())
                        .intValue();
        int numberOfLowercaseLetters =
                Long.valueOf(input.chars().filter(c -> Character.isLowerCase(c)).count())
                        .intValue();
        System.out.println("The lenght of the String is " + input.length()
                + " number of uppercase letters " + numberOfUppercaseLetters
                + " number of lowercase letters " + numberOfLowercaseLetters);
    }
}

Sample input:

saveChangesInTheEditor

Sample output:

The lenght of the String is 22 number of uppercase letters 4 number of lowercase letters 18

Mohammad
  • 6,024
  • 3
  • 22
  • 30
-1

You simply loop over the content and use the Character features to test it. I use real codepoints, so it supports supplementary characters of Unicode.

When dealing with code points, the index cannot simply be incremented by one, since some code points actually read two characters (aka code units). This is why I use the while and Character.charCount(int cp).

/** Method counts and prints number of lower/uppercase codepoints. */
static void countCharacterClasses(String input) {
    int upper = 0;
    int lower = 0;
    int other = 0;

    // index counts from 0 till end of string length
    int index = 0;
    while(index < input.length()) {
        // we get the unicode code point at index
        // this is the character at index-th position (but fits only in an int)
        int cp = input.codePointAt(index);
        // we increment index by 1 or 2, depending if cp fits in single char
        index += Character.charCount(cp);

        // the type of the codepoint is the character class
        int type = Character.getType(cp);
        // we care only about the character class for lower & uppercase letters
        switch(type) {
            case Character.UPPERCASE_LETTER:
                upper++;
                break;
            case Character.LOWERCASE_LETTER:
                lower++;
                break;
            default:
                other++;
        }
    }

    System.out.printf("Input has %d upper, %d lower and %d other codepoints%n",
                      upper, lower, other);
}

For this sample the result will be:

// test with plain letters, numbers and international chars:
countCharacterClasses("AABBÄäoßabc0\uD801\uDC00");
      // U+10400 "DESERET CAPITAL LETTER LONG I" is 2 char UTF16: D801 DC00

Input has 6 upper, 6 lower and 1 other codepoints

It count the german sharp-s as lowercase (there is no uppercase variant) and the special supplement codepoint (which is two codeunits/char long) as uppercase. The number will be counted as "other".

Using Character.getType(int cp) instead of Character.isUpperCase() has the advantage that it only needs to look at the code point once for multiple (all) character classes. This can also be used to count all different classes (letters, whitespace, control and all the fancy other unicode classes (TITLECASE_LETTER etc).

For a good background read on why you need to care about codepoints und units, check out: http://www.joelonsoftware.com/articles/Unicode.html

eckes
  • 10,103
  • 1
  • 59
  • 71