Convert letters into numbers
I need to write a method that converts letters from a word into a number according to the telephone buttons.
I figured I was at a good start by putting the string of the word into a character array, but how would I assign each of those letters to its corresponding number?
Thanks in advance.
u can use switch statement
sample
switch(button) {
case 'A':
case 'B':
case 'C:
System.out.println("2");
break;
case 'D':
case 'E':
case 'F:
System.out.println("3");
break;
//and so fort and so on
}
> I need to write a method that converts letters from a
> word into a number according to the telephone
> buttons.
>
> I figured I was at a good start by putting the string
> of the word into a character array, but how would I
> assign each of those letters to its corresponding
> number?
I'm not sure myself as I'm still learning about this type of stuff, but it sounds like some kind of Hash storage like a HashMap would work well here.
addendum: just saw the answer above, and switch could work well here too.
Message was edited by:
petes1234
> u can use switch statement
>
> sample
> > switch(button) {
>case 'A':
> case 'B':
>case 'C:
>System.out.println("2");
>break;
> case 'D':
>case 'E':
> case 'F:
> System.out.println("3");
> break;
> //and so fort and so on
> }
Thanks I'll try that now. I had tried a switch, but not in that way.
I did the following but I get an error at the bold saying that I cant switch on a value of type char[]
public class Testing
{
public static void main(String[] args)
{
String a = "freebee";
char[ ] lettersToNumber = a.toUpperCase().toCharArray();
[b]switch(lettersToNumber)[/b] {
case 'A':
case 'B':
case 'C':
System.out.println("2");
break;
case 'D':
case 'E':
case 'F':
System.out.println("3");
break;
case 'G':
case 'H':
case 'I':
System.out.println("4");
break;
case 'J':
case 'K':
case 'L':
System.out.println("5");
break;
case 'M':
case 'N':
case 'O':
System.out.println("6");
break;
case 'P':
case 'Q':
case 'R':
case 'S':
System.out.println("7");
break;
case 'T':
case 'U':
case 'V':
System.out.println("8");
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
System.out.println("9");
break;
}
System.out.println( a );
}
}
well, the line with the bolding code haha
I think you need to have a loop... I might be wrong, pardon me =)I'm a beginner too. But I feel that a loop is absent
> I think you need to have a loop... I might be wrong,> pardon me =)> > I'm a beginner too. But I feel that a loop is absentIt's all right. A loop is actually what I needed. It works. Thanks everyone. =]
I tried to implement this as a hashmap just for academic purposes. I'm not suggesting this as a solution, but again, since I'm just now learning about hash's, I figured wtf, let's do it this way. If anyone sees any bugs, misuses of HashMap or other problems, please let me know:
import java.util.HashMap;
import java.util.Map;
class HashMapTester
{
private Map<Character, Integer> phoneHash;
// for converting alphabetical characters to numbers based on the
// phone dialing pad.
public HashMapTester()
{
phoneHash = new HashMap<Character, Integer>();
for (char myChar = 'a'; myChar <= 'o'; myChar++)
{
// enter all letters from 'a' to 'o' into map
int number = (int)(2 + (myChar - 'a') / 3);
phoneHash.put(myChar, number);
phoneHash.put(Character.toUpperCase(myChar), number);
}
for (char myChar = 'p'; myChar <= 's'; myChar++)
{
phoneHash.put(myChar, 7);
phoneHash.put(Character.toUpperCase(myChar), 7);
}
for (char myChar = 't'; myChar <= 'v'; myChar++)
{
phoneHash.put(myChar, 8);
phoneHash.put(Character.toUpperCase(myChar), 8);
}
for (char myChar = 'w'; myChar <= 'z'; myChar++)
{
phoneHash.put(myChar, 9);
phoneHash.put(Character.toUpperCase(myChar), 9);
}
}
// convert string to a long number based on results of
// the string's characters run through the hashmap
public long convertStr(String s) throws IndexOutOfBoundsException
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++)
{
char myChar = s.charAt(i);
if ((myChar >= 'a' && myChar <= 'z') || (myChar >= 'A' && myChar <= 'Z'))
{
sb.append(phoneHash.get(myChar));
}
else
{
throw new IndexOutOfBoundsException();
}
}
return Long.valueOf(sb.toString());
}
public static void main(String[] args)
{
HashMapTester hmt = new HashMapTester();
System.out.println(hmt.convertStr("aaa"));
System.out.println(hmt.convertStr("What"));
System.out.println(hmt.convertStr("the"));
System.out.println(hmt.convertStr("heck"));
System.out.println(hmt.convertStr("Fubar"));
System.out.println(hmt.convertStr("Snafu"));
System.out.println(hmt.convertStr("abcdefghijklm"));
System.out.println(hmt.convertStr("nopqrstuvwxyz"));
}
}
Message was edited by:
petes1234
> I think you need to have a loop...
I agree.
And I think you would make thing a lot simpler if you moved the switch business into another method. (It's the sort of thing that seems like it might be useful on other occasions.)static int charToInt(char ch) {
switch(ch) {
case 'A':
case 'B':
case 'C':
return 1;
case 'D:
case 'E:
case 'F':
return 2;
// etc
}
return -1; // or something. IllegalArgumentException?
}
Then your loop could look like:public static void main(String[] args) {
String str = "freebee";
char[] chArr = str.toUpperCase().toCharArray();
for(int i = 0; i < chArr.length; i++) {
int num = charToInt(chArr[i]);
// do something with num
}
}
> I tried to implement this as a hashmap just for
> academic purposes. I'm not suggesting this as a
> solution, but again, since I'm just now learning
> about hash's, I figured wtf, let's do it this way.
> If anyone sees any bugs, misuses of HashMap or other
> problems, please let me know:
>
I actually have to put mine in a map as well. Key of phone numbers and list of words as values.
Your program works very well. Good job.
changes to code that fills the hashmap. more concise (less interpretable)
import java.util.HashMap;
import java.util.Map;
class HashMapTester2
{
private Map<Character, Integer> phoneHash;
// constructor
// for converting alphabetical characters to numbers based on the
// phone dialing pad.
public HashMapTester2()
{
phoneHash = new HashMap<Character, Integer>();
fillMap();
}
private void fillMap()
{
for (char myChar = 'a'; myChar <= 'z'; myChar++)
{
int distanceFrom_a = (int)(myChar - 'a');
if (myChar > 'r') // 's' hangs back w/ the pqr group.
distanceFrom_a -= 1;
if (myChar > 'y') // 'z' hangs back w/ the wyz group.
distanceFrom_a -= 1;
// 2 is due to the numbers starting at 2
// 3 is due to the letters being grouped in 3's, all sharing
// the same number.
int number = (int)(2 + (distanceFrom_a) / 3);
phoneHash.put(myChar, number); // insert reg char
// insert uppercase version, same number
phoneHash.put(Character.toUpperCase(myChar), number);
}
}
// convert string to a long number based on results of
// the string's characters run through the hashmap
public long convertStr(String s) throws IndexOutOfBoundsException
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++)
{
char myChar = s.charAt(i);
if ((myChar >= 'a' && myChar <= 'z') || (myChar >= 'A' && myChar <= 'Z'))
{
sb.append(phoneHash.get(myChar));
}
else
{
throw new IndexOutOfBoundsException();
}
}
return Long.valueOf(sb.toString());
}
public static void main(String[] args)
{
HashMapTester2 hmt = new HashMapTester2();
System.out.println(hmt.convertStr("aaa"));
System.out.println(hmt.convertStr("What"));
System.out.println(hmt.convertStr("the"));
System.out.println(hmt.convertStr("heck"));
System.out.println(hmt.convertStr("Fubar"));
System.out.println(hmt.convertStr("Snafu"));
System.out.println(hmt.convertStr("abcdefghijklm"));
System.out.println(hmt.convertStr("nopqrstuvwxyz"));
System.out.println();
System.out.println(hmt.convertStr("abc"));
System.out.println(hmt.convertStr("def"));
System.out.println(hmt.convertStr("ghi"));
System.out.println(hmt.convertStr("jkl"));
System.out.println(hmt.convertStr("mno"));
System.out.println(hmt.convertStr("pqrs"));
System.out.println(hmt.convertStr("tuv"));
System.out.println(hmt.convertStr("wxyz"));
}
}
You guys have all gone code crazy ;)... there's no need for HashMaps. I like the lo-fi, less-code approach...
public class L2N {
private String letters = "abcdefghijklmnopqrstuvwxyz";
private String numbers = "22233344455566677778889999";
private char getNumber(char letter) {
int index = letters.indexOf(letter);
if (index < 0) {
index = letters.toUpperCase().indexOf(letter);
}
if (index < 0) {
return letter;
} else {
return numbers.charAt(index);
}
}
public String getNumbers(String letters) {
String numbers = "";
for (int i = 0; i < letters.length(); i++) {
numbers += getNumber(letters.charAt(i));
}
return numbers;
}
public static void main(String [] args) {
L2N l2n = new L2N();
System.out.println(l2n.getNumbers("Howdy, neighbor!"));
System.out.println(l2n.getNumbers("What's wrong with lo-fi?"));
}
}
kev@mymachine:~/Desktop$ java L2N
46939, 63444267!
9428'7 97664 9484 56-34?
>You guys have all gone code crazy ;)... there's no need for HashMaps. I like the lo-fi, less-code approach...nice approach man! hehe... thumbs up!!but of course there are times that you need to be hi-fi... and i think most of the time.. ^_*
> nice approach man! hehe... thumbs up!!
> but of course there are times that you need to be
> hi-fi... and i think most of the time.. ^_*
Thanks. You're right, the hi-fi approach is normally the right way to go. In this case, cutting the corners worked simply because you're doing single-character replacement. The other approaches here would be more flexible if the problem changed slightly.
> You guys have all gone code crazy ;)... there's no
> need for HashMaps. I like the lo-fi, less-code
> approach...
>
Of course yours is better than mine... Anyway, like I said, I just did mine to play with hashmaps. Yours is much more pragmatic, and I like the way when the string's are laid out directly under each other you can see at a glance the number that correlates to the letter. (BTW, what exactly is hi-fi in this situation?)
Also kevjava, you didn't really lose data, did you? Again, sorry!
> Anyway, like I said, I just did mine to play with hashmaps.
I don't know how, but I missed that, actually :). Sorry, I didn't mean anything negative by my post.
What I meant by yours being more flexible: Say we're done using the phone alphabet, and we now want to use the NATO phonetic alphabet.
Alpha, Bravo, Charlie, Delta, Echo, Foxtrot...
My algorithm is worthless in this scenario. With yours, you retool the fillMap() method.
So, doing it with the Hi-Fi, Super-Octane, Object-Orientated tactic :) (in this case, for entirely academic purposes) certainly has its place.
> I don't know how, but I missed that, actually :).> Sorry, I didn't mean anything negative by my post.I didn't take it negatively. It's just you're more experienced. Your a better coder.
I don't have a phone with the numbers in front of me so i'm not sure it would work but what about the following :
Take the letter convert to upper case, take the number and make it so a starts at 0(don't know the ascii value that A or a starts at off the top of my head) and mod by 3 and the whole number is the number you need to output. Just thought I would throw my 2 cents in for good measure ;-P
*Edited to fix small error*
Mod by 3? Nope. Look at the letters on your "7" button to see why not.
Am I too late to join da show?
public class CharToNumber {
static String [] alpha = {"abc", "def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public static void main(String[] args) {
printNumber("tonumber");
}
static void printNumber(String s ) {
for (int j = 0; j < s.length(); j++) {
for (int i = 0; i < alpha.length; i++) {
if(alpha[i].indexOf(s.charAt(j))>-1) {
System.out.print(i+2);
}
}
}
}
}
Also what about 0 and 1? They have some funky symbols on my phone.
Message was edited by:
_helloWorld_