Search code examples
javastringnumbersletters

Numbers to letters in java (like old mobile phones' keyboard)


Just like older mobile phones' keypads work. I should input a string of numbers and the program should print out a text based on those numbers.

e.g: Input: 4448 9666777557777 should output to: ITWORKS.

Here's my code so far but it's not printing out anything. Could you please tell me what's wrong with it and what could've I done better?

    Scanner sc = new Scanner(System.in);

    String[] letters = {
            "0",
            "1",
            "ABC",
            "DEF",
            "GHI",
            "JKL",
            "MNO",
            "PQRS",
            "TUV",
            "WXYZ"
    };

    System.out.println("Write something.");
    String numbers = sc.nextLine();

    char[] toChar = numbers.toCharArray();
    int count = 0;

    for (int index = 0; index < toChar.length; index++) {
        if (toChar[index] >= '2' && toChar[index] <= '9') {
            if (index > 0 && toChar[index] == toChar[index - 1]) {
                count++;
            }
            else if (count > 0) {
                System.out.print(letters[toChar[index - 1] - '0'].charAt(count - 1));
                count = 0;              
            }
        }
    }

Solution

  • How about this?

    import java.util.Scanner;
    
    public class Test {
        private static final String[] letters = {
                "0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
        };
    
        private static char getChar(int digit, int count) {
            while (count > letters[digit].length()) {
                count -= letters[digit].length();
            }
    
            return letters[digit].charAt(count - 1);
        }
    
        private static String getString(String input) {
            int lastDigit = 0, count = 1;
            String result = "";
    
            for (int i = 0; i < input.length(); i++) {
                int currentDigit = input.charAt(i) - '0';
                if (currentDigit >= 2 && currentDigit <= 9) {
                    if (lastDigit == 0) {
                        lastDigit = currentDigit;
                    } else if (currentDigit == lastDigit) {
                        count++;
                    } else {
                        result += getChar(lastDigit, count);
    
                        lastDigit = currentDigit;
                        count = 1;
                    }
                }
            }
    
            return result + getChar(lastDigit, count);
        }
    
        public static void main(String[] args) {
            try (Scanner scanner = new Scanner(System.in)) {
                System.out.println("Write something");
                System.out.println(getString(scanner.nextLine()));
            }
        }
    }
    

    I enhanced the problem decomposition. It works for all examples OP has shown so far.