Problem:
The purpose of this program is to demonstrates the relationship between arrays an strings. Create an application that reads a sentence from the user and counts the number of uppercase and lowercase letters contained in it.
Output:
Enter a sentence:
Hello, I'm reading a sentence on "javaproblems.com". Yey me!
A: 0 a: 4
B: 0 b: 1
C: 0 c: 2
D: 0 d: 1
E: 0 e: 8
F: 0 f: 0
G: 0 g: 1
H: 1 h: 0
I: 1 i: 1
J: 0 j: 1
K: 0 k: 0
L: 0 l: 3
M: 0 m: 4
N: 0 n: 4
O: 0 o: 4
P: 0 p: 1
Q: 0 q: 0
R: 0 r: 2
S: 0 s: 2
T: 0 t: 1
U: 0 u: 0
V: 0 v: 1
W: 0 w: 0
X: 0 x: 0
Y: 1 y: 1
Z: 0 z: 0
Non-alphabetic characters: 15
Hello, I'm reading a sentence on "javaproblems.com". Yey me!
A: 0 a: 4
B: 0 b: 1
C: 0 c: 2
D: 0 d: 1
E: 0 e: 8
F: 0 f: 0
G: 0 g: 1
H: 1 h: 0
I: 1 i: 1
J: 0 j: 1
K: 0 k: 0
L: 0 l: 3
M: 0 m: 4
N: 0 n: 4
O: 0 o: 4
P: 0 p: 1
Q: 0 q: 0
R: 0 r: 2
S: 0 s: 2
T: 0 t: 1
U: 0 u: 0
V: 0 v: 1
W: 0 w: 0
X: 0 x: 0
Y: 1 y: 1
Z: 0 z: 0
Non-alphabetic characters: 15
Solution:
import java.util.Scanner; public class LetterCount { public static void main (String[] args) { final int NUMCHARS = 26; Scanner scan = new Scanner (System.in); int[] upper = new int[NUMCHARS]; int[] lower = new int[NUMCHARS]; char current; // the current character being processed int other = 0; // counter for non-alphabetics System.out.println ("Enter a sentence:"); String line = scan.nextLine(); for (int ch = 0; ch < line.length(); ch++) { current = line.charAt(ch); if (current >= 'A' && current <= 'Z') upper[current-'A']++; else if (current >= 'a' && current <= 'z') lower[current-'a']++; else other++; } System.out.println (); for (int letter=0; letter < upper.length; letter++) { System.out.print ( (char) (letter + 'A') ); System.out.print (": " + upper[letter]); System.out.print ("\t\t" + (char) (letter + 'a') ); System.out.println (": " + lower[letter]); } System.out.println (); System.out.println ("Non-alphabetic characters: " + other); } }
No comments :
Post a Comment