This is a class for a JOptionPane.showInputDialog program, that is created in order to take a string of characters as input (words or #s) and convert it to a numeric phone number based on the traditional touch tone telephone keypad as output message. Okay here is the class for the program (actual JOptionPane main program code is not really relevant to this topic, so I did not include it):
public class Phone
{
private String word = "";
private String number = "";
public Phone(String word)
{
this.word = word;
setNumber();
}
public void setNumber()
{
for(int i = 0; (i < word.length() && i < 7); i++)
{
word.toLowerCase();
char c = word.charAt(i);
switch(c)
{
case '0': number += "0"; break;
case '1': number += "1"; break;
case '2': number += "2"; break;
case '3': number += "3"; break;
case '4': number += "4"; break;
case '5': number += "5"; break;
case '6': number += "6"; break;
case '7': number += "7"; break;
case '8': number += "8"; break;
case '9': number += "9"; break;
}
}
if(number.length() > 3)
number = number.substring(0,3) + "-" + number.substring(3);
else
number = number;
}
public String toString()
{
return number;
}
}
I want to know how to use this switch statement in the above class for cases 2 - 9 to not only check for the numerical values on a phone touch tone keypad but also each of the three letter chars as well. For example I really want to be able to do something like this, but it will not let me do it in java:
public class Phone
{
private String word = "";
private String number = "";
public Phone(String word)
{
this.word = word;
setNumber();
}
public void setNumber()
{
for(int i = 0; (i < word.length() && i < 7); i++)
{
word.toLowerCase();
char c = word.charAt(i);
switch(c)
{
case '0': number += "0"; break;
case '1': number += "1"; break;
case '2', 'a', 'b', 'c': number += "2"; break;
case '3', 'd', 'e', 'f': number += "3"; break;
case '4', 'g', 'h', 'i': number += "4"; break;
case '5', 'j', 'k', 'l': number += "5"; break;
case '6', 'm', 'n', 'o': number += "6"; break;
case '7', 'p', 'r', 's': number += "7"; break;
case '8', 't', 'u', 'v': number += "8"; break;
case '9', 'w', 'x', 'y': number += "9"; break;
}
}
if(number.length() > 3)
number = number.substring(0,3) + "-" + number.substring(3);
else
number = number;
}
public String toString()
{
return number;
}
}
Now, I want to know if it is possible to do what Java will not let me do in the above second written code using a switch statement (basically check to see if any of the chars match the case at hand). I already know I could use a if statement to do this with no problem I imagine other than the fact that I think it would be more code writing than just using a switch statement. I just want to know basically why I can't get the switch statement or syntax for this matter to work & compile in Java like I want.