需要帮助调试和格式化建议

时间:2019-03-24 14:55:15

标签: java string

我有一个作业要编写代码,该代码将输入的电话号码(例如555-HAM-SAND)转换为数字字符串。我应该只使用IVE在本书的两部分中学到的内容,这些内容涵盖了Character测试以及使用Character类进行的转换以及其他字符串方法。

import javax.swing.JOptionPane;
import java.util.Scanner;

public class TelephoneNumberTranslator2
{
   public static void main(String[] args)
   {
      String input;
      String number = "";
      int phoneNumber;
      char ch;

      input = JOptionPane.showInputDialog("Please enter a 10-digit phone number. (Including dashes)\nEx: 123-HAM-SAND");

      if (input.length() != 12)
         input = JOptionPane.showInputDialog("That is not a proper number.\nUse a format of XXX-XXX-XXXX.\n(Include dashes)");

      phoneNumber = input.length();


      for (int i=0; i < phoneNumber; i++)
         number = number + translate(input.charAt(i));


      JOptionPane.showMessageDialog(null, number);

      System.exit(0);

   }


   public static String translate(char ch)
   {  
      if (Character.isDigit(ch))
         return String.valueOf(ch);
      else if (Character.isLowerCase(ch))
         ch = Character.toUpperCase(ch);
      else if (Character.isUpperCase(ch))
      {
         if (ch == 'A' || ch == 'B' || ch == 'C')
            return "2";
         if (ch == 'D' || ch == 'E' || ch == 'F')
            return "3";
         if (ch == 'G' || ch == 'H' || ch == 'I')
            return "4";
         if (ch == 'J' || ch == 'K' || ch == 'L')
            return "5";
         if (ch == 'M' || ch == 'N' || ch == 'O')
            return "6";
         if (ch == 'P' || ch == 'Q' || ch == 'R' || ch == 'S')
            return "7";
         if (ch == 'T' || ch == 'U' || ch == 'V')
            return "8";
         if (ch == 'W' || ch == 'X' || ch == 'Y' || ch == 'Z')
            return "9";   
       }
       else
         return String.valueOf(ch);
   }
}

我目前遇到丢失的return语句错误,无法找出原因。另外,我也不知道这是执行任务的正确方法还是使用字符串和字符方法的更好方法。任何反馈表示赞赏!

0 个答案:

没有答案