标签:
之前用java做过0-99的数字和英文之间的翻译,输入数字就会翻译成英文,输入英文会翻译成数字,比如输入56 输出fiftysix 输入fiftysix 输出56,
发现这会有一个异常,当输入不符合格式时,比如英文和数字混输,或者输入标点会报NumberFormatException异常,现在捕捉了这个异常,顺便把
输入越界也加入了异常,比如输入100时 报"输入越界!"。
以下附上代码:
package TranslateClass;
import java.util.Scanner;
abstract class inter
{
String x[]={"zero","one","two","three","four","five","six","seven","eight","nine"};
String y[]={"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
String z[]={"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"};
abstract void Translate()throws OutException;
}
class OutException extends Exception
{
OutException(String msg)
{
super(msg);
}
}
class TransEnglish extends inter//数字翻译成英文
{
int a;
TransEnglish(int a)
{
this.a=a;
}
public void Translate()throws OutException
{
if(a>=0&&a<=9)
System.out.println(a+" 翻译成英文为:\n"+x[a]);
else if(a>9&&a<=19)
System.out.println(a+" 翻译成英文为:\n"+y[a%10]);
else if(a>19&&a<=99)
System.out.println(a+" 翻译成英文为:\n"+z[a/10-2]+"-"+x[a%10]);
else
throw new OutException("输入的数字"+a+"不在0-99之间!");
}
}
class TransCout extends inter//英文翻译成数字
{
String a;
int i;
int j=0;
TransCout(String a)
{
this.a=a;
}
public void Translate()throws OutException
{
for(i=0;i<=7;i++)
{
if(a.contains(z[i]))
j=(i+2)*10;
if(a==z[i])
{
System.out.println(a+" 翻译成数字为\n"+(i+2)*10);
return;
}
}
for(i=0;i<=9;i++)
{
if(a==y[i])
{
System.out.println(a+" 翻译成数字为\n"+i+10);
return;
}
else if(a.contains(x[i]))
{
System.out.println(a+" 翻译成数字为\n"+(j+i));
return;
}
}
throw new OutException("输入的英文"+a+"不在zero 到 ninety-nie之间!");
}
}
class Translate
{
private Translate(){}
private static Translate s= new Translate();
public static Translate getTranslate()
{
return s;
}
public void Trans()
{
System.out.print("请输入你想翻译的数字或英文(仅限0-99):");
Scanner scanf=new Scanner(System.in);
try//解决输入格式异常
{
String Str=scanf.next();
if(Str.charAt(0)>=48&&Str.charAt(0)<=57)
{
int cot=Integer.parseInt(Str);
new TransEnglish(cot).Translate();
}
else
new TransCout(Str).Translate();
}
catch(NumberFormatException e)
{
System.out.println("输入错误!");
System.out.println(e.toString());
}
catch(OutException o)
{
System.out.println("输入越界!");
System.out.println(o.toString());
}
finally
{
System.out.println("翻译结束。");//断开服务器连接
}
}
public static void main(String[] args)
{
Translate T = Translate.getTranslate();
T.Trans();
//new Translate().Trans();
}
}
标签:
原文地址:http://www.cnblogs.com/zdy1093979553/p/5364935.html