Program opened below. You can scroll through the algorithm, Java code and output.

Telephone Keypad Keystrokes

Download .java

Question

Accept one alphabetic word without punctuation, digits or spaces. Calculate the number of repeated key presses required on a traditional mobile keypad (ABC=2, DEF=3, ..., WXYZ=9).

Step 1: Start. Step 2: Declare the variables and data structures required for the task. Step 3: Input the word and convert it to upper case. Step 4: Validate that every character is A..Z. Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution. Step 6: Create a mapping from each letter to its keypad digit and press position. Step 7: For each letter, add its position within its key group to the total. Step 8: Store the computed result and prepare it for display. Step 9: Store the computed result and prepare it for display. Step 10: Display the total number of keystrokes. Step 11: Stop.
Java
import java.util.*;
class KeypadStrokes {
    static final String[] keys = {
        "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
    }
;
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String word = sc.nextLine().trim().toUpperCase(Locale.ROOT);
    if (!word.matches("[A-Z]+")) {
        System.out.println("INVALID ENTRY");
        return;
    }
int total = 0;
for (char c : word.toCharArray()) {
    for (String key : keys) {
        int pos = key.indexOf(c);
        if (pos >= 0) {
            total += pos + 1;
            break;
        }
}
}
System.out.println("Number of keystrokes = " + total);
}
}
Input: DEAR Output: Number of keystrokes = 7
← Previous Program 84 of 84

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.