0

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;              
            }
        }
    }
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user3060096
  • 85
  • 4
  • 13
  • 1
    Think what happens if a telephone number have 2 same digits one after another. Should for example `7777` be projected into one `S` (7777) or two `Q`s (77 + 77), or maybe it is `PR` (7 + 777)... – Alex Salauyou Mar 30 '15 at 16:20
  • I'm pretty sure (7777) should always equal to S, (77777) to SP, (777777) to SQ, etc. – user3060096 Mar 30 '15 at 16:30
  • 2
    Using this kind of encoding there is no way to get `QR` or `PS` for example (because they both will be encoded to `77777` and decoded into `SQ`) – Alex Salauyou Mar 30 '15 at 16:37
  • Oh, yes. I understand. Well... When I think about it now `77777` should equal to `P` - a.k.a rotate around the 4 letters until it sees a number != 7. – user3060096 Mar 30 '15 at 16:44
  • Did you see my answer? It solves all the issues. – tzima Mar 30 '15 at 17:10

3 Answers3

1

If I understand your intention correctly, count should increment only if current digit is the same as previous:

for (int pos = 1, char c = toChar[0], int count = 1; pos <= toChar.length; pos++, count = 1) {

   int n = letters[c - '0'].length;
   while (pos < toChar.length && c == toChar[pos] && count < n) {
       pos++;
       count++;
   }
   System.out.println(letters[c - '0'].charAt(count - 1));
   if (pos < toChar.length - 1) {
       c = toChar[++pos];
   }
}
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
1

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.

tzima
  • 1,285
  • 1
  • 10
  • 23
  • Thank you! Accepted your answer. It's similar to mine as an idea yet works flawlessly! Could you please explain why do you return `result + getChar(lastDigit, count)` at the end instead of simply `result`, though? – user3060096 Mar 30 '15 at 17:15
  • 1
    Well, for the last sequence of the input, it doesn't reach the "else" part of that condition. The code, how it is, basically "reacts" on the change -- a new digit (e.g.: "777|8..." - 8 is the change). For the last sequence of the input, such change doesn't occur. It'd be possible to change the code so it evaluates the 'else' part on change OR end of string. – tzima Mar 30 '15 at 17:19
  • Do you have any idea how could I possibly introduce intervals ' ' as delimiters in the aforementioned code, by the way? – user3060096 Mar 31 '15 at 14:59
0

This code will help you! Check this one

public class Denene {
    public static String getChar(String cha)
    {
        String [] chars= {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        String[] strSplit = cha.split(" "); //7777 88 7777 2 66 8
        int len=strSplit.length;
        char r;
        char []ar =new char[len];
      for(int i=0;i<len;i++){
          String str=strSplit[i];
          ar[i]= chars[Integer.parseInt(String.valueOf(str.charAt(0)))].charAt(str.length()-1);
        }
        return new String(ar);
    }
        public static void main(String[] args) {
            System.out.println("Enter any number .....");
           System.out.println(getChar(new Scanner(System.in).nextLine())); //Output : susant
        }
    }