Issue
I'm on course and we've recently started learning Java. I've got a task identify pangrams using switch-cases and booleans. The task states:
Create a String ‘sentence’ with the value “Sixty zippers were quickly picked from the woven jute bag.”
Create 26 Boolean variables named a to z
a. Boolean a, b, … y, z;
b. a, b, … y, z = true;
Create a loop that will iterate over each letter of the sentence
a. Be careful of the iterator you use within your loop as the letter ‘i’ will already be taken!
Using switch-cases and the Booleans you made, identify the letter and set the corresponding Boolean to true.
Once the sentence has been fully processed, evaluate the value of each Boolean:
a. Should all of them be true, print the message ‘the sentence “” is a pangram!’
b. Should any of them be false, print the message ‘the sentence “” is not a pangram!’
I'm not sure if it's just the wording of the task that's tripping me up, but I'm not sure how to execute it. This is what I've got at the moment:
String sentence = "Sixty zippers were quickly picked from the woven jute bag.";
Boolean a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
a = b = c = d = e = f = g = h = i = j = k = l = m = n = o = p = q = r = s = t = u = v = x = y = z = true;
for (int letter = sentence.length() - 1; letter <= 0; letter++) {
int character = sentence.charAt(letter);
switch(character) {
case a:
case b:
case c:
When I do the case like this, obviously it won't convert, so how would I evaluate each character?
Solution
As pointed out in the comments, the for loop is not correct. To iterate over the characters in order:
for (int letter = 0; letter < sentence.length(); letter++) {
When fetching a character from the string, convert it to lower case (otherwise, you'd need a separate case
for both 'a'
and 'A'
):
char character = Character.toLowerCase(sentence.charAt(letter));
The switch statement:
switch(character) {
case 'a':
a = false;
break; // needed to avoid fall-through to case 'b'
case 'b':
b = false;
break;
...
Now you can test if all variables were set to false:
boolean isPangram = !a && !b && ... && !z;
The code would be simpler and clearer if the variables were set to false
in the beginning and to true
in the loop.
Answered By - Michel K
Answer Checked By - Senaida (JavaFixing Volunteer)