Define a class to accept a String and print if it is a Super String or not. A String is Super if the number of uppercase letters is equal to the number of lowercase letters. [Use Character & String methods only] Example: "COmmITmeNt" Number of Uppercase letters = 5 Number of Lowercase letters = 5 String is a Super String
Topic: String and Character methods — Super String
Answer
import java.util.Scanner;
class SuperString { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a String : "); String str = sc.nextLine();
int uc = 0, lc = 0; char ch;
for(int i = 0; i < str.length(); i++) { ch = str.charAt(i); if(Character.isUpperCase(ch)) uc++; else if(Character.isLowerCase(ch)) lc++; }
System.out.println("Number of Uppercase letters = " + uc); System.out.println("Number of Lowercase letters = " + lc);
if(uc == lc) System.out.println("String is a Super String"); else System.out.println("String is not a Super String"); } }
The standard shape for every character-counting question: read the string, loop from 0 to length() - 1, pull out each character with charAt(i), and test it.
The instruction "[Use Character & String methods only]" is an instruction, not a hint — comparing with ch >= 65 && ch <= 90 will lose marks. Use Character.isUpperCase() and Character.isLowerCase().
Note why the second test is else if and not a plain if. A digit, space or symbol is neither upper nor lower case, and else if lets such characters fall through without being counted. This matters for a string like "Ab 12 Cd".
Take care with input: use nextLine() rather than next(), because a Super String may contain spaces and next() would read only the first word.
Trace the example: C, O, I, T, N are uppercase (5) and m, m, m, e, t are lowercase (5), so the counts match and the string is Super.
str String - the string entered by the user ch char - holds each character of str in turn uc int - counter for uppercase letters lc int - counter for lowercase letters i int - loop variable, the index into the string sc Scanner - object used to read input from the keyboard