以下是我尝试使用J Creator LE制作的代码。 我现在还处于初学阶段,我希望你能帮助我。
public class TelNumHelper{
public static void main(String[] Args){
String input = "1-800-FLO-WERS";
String output = " ";
int Key2,Key3,Key4,Key5,Key6,Key7,Key8,Key9,Key0;
Key2 = 2;
Key3 = 3;
Key4 = 4;
Key5 = 5;
Key6 = 6;
Key7 = 7;
Key8 = 8;
Key9 = 9;
Key0 = 0;
for(int i = 0;i<input.length();i++){
if(input.charAt(i)=='-'){
output = output + input.charAt(i);
}else{
output = output + valid(input.charAt(i));
}
}
public static char valid(char input){
if(input == A||input == B||input == C||input == 2){
System.out.println(Key2);
}else if(input == D||input == E||input == F||input == 3){
System.out.println(Key3);
}else if(input == G||input == H||input == I||input == 4){
System.out.println(Key4);
}else if(input == J||input == K||input == L||input == 5){
System.out.println(Key5);
}else if(input == M||input == N||input == O||input == 6){
System.out.println(Key6);
}else if(input == P||input == Q||input == R||input == S||input == 7){
System.out.println(Key7);
}else if(input == T||input == U||input == V||input == 8){
System.out.println(Key8);
}else if(input == W||input == X||input == Y||input == Z||input == 9){
System.out.println(Key9);
}else if(input == 0){
System.out.println(Key0);
}else{
System.out.println("Error");
}
}
}
}
如何使方法有效? 我尝试使用不同类型的方法,但它仍然无法正常工作
此代码应输出数字而不是字符,每个字符都应更改为数字。我用手机键盘作为将字符变成数字的基础。
答案 0 :(得分:1)
您的valid
方法会打印字符而不是返回它们。除了表明此方法进行某种验证的名称外,if
个案必须使用return
。
您已将键定义为整数,但您确实希望返回具有适当数字的字符。而且你必须与字符进行比较,而不是一些称为A,B等的静态变量。你应该是这样的:
char Key1 = '1';
char Key2 = '2';
...
public static void Main(string[] args) {
string input = "0-800-FLO-WERS";
string output = "";
for(....)...
}
public static char valid(char input)
{
if ((input == 'A') || (input == 'B') ... )
return Key1;
else if ....
}
答案 1 :(得分:0)
如果你按照编译和测试的方式进行编译和测试,你就不会编写那么多需要稍后修复的代码。通常在翻译中,有一些映射更简单。这是你可以做到的一种方式
public class Main {
static final String codes = "00000" +
"11111" +
"22ABC" +
"33DEF" +
"44GHI" +
"55JKL" +
"66MNO" +
"7PQRS" +
"88TUV" +
"9WXYZ";
public static void main(String... ignore) {
String input = "1-800-FLO-WERS";
String output = convertTextToDigits(input);
System.out.println(input + " can be dialed as " + output);
}
private static String convertTextToDigits(String input) {
StringBuilder sb = new StringBuilder(input.length());
for(char ch: input.toCharArray()) {
int pos = codes.indexOf(ch);
if (pos >=0)
sb.append(pos/5);
}
return sb.toString();
}
}
打印
1-800-FLO-WERS can be dialed as 18003569377