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" }; 用Java命令行输入或在Eclipse中设置参数一个小于100的整数,将其翻成英文表示。 例如: 输入32,输出:thirty two 输入14,输出:fourteen 输入8, 输出:eight 反之,输入英文表示,输出相应的整数,例如输入 fifty one,输出 51。
时间: 2023-06-29 07:16:56 浏览: 134
详解C#中的string与String
好的,我可以帮您实现这个功能。以下是代码实现:
```
import java.util.*;
public class NumberToEnglish {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个小于100的整数或英文单词:");
String input = scanner.nextLine();
if (isNumeric(input)) {
int num = Integer.parseInt(input);
if (num < 10) {
System.out.println(getDigit(num));
} else if (num < 20) {
System.out.println(getTeen(num));
} else {
System.out.println(getTens(num / 10) + " " + getDigit(num % 10));
}
} else {
String[] words = input.split(" ");
if (words.length == 1) {
System.out.println(getDigit(words[0]));
} else if (words.length == 2) {
System.out.println(getTens(words[0]) + " " + getDigit(words[1]));
}
}
}
private static boolean isNumeric(String str) {
try {
int d = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
private static String getDigit(int num) {
String[] x = {"zero","one","two","three","four","five","six","seven","eight","nine"};
return x[num];
}
private static String getDigit(String word) {
String[] x = {"zero","one","two","three","four","five","six","seven","eight","nine"};
for (int i = 0; i < x.length; i++) {
if (x[i].equals(word)) {
return Integer.toString(i);
}
}
return null;
}
private static String getTeen(int num) {
String[] y = {"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
return y[num - 10];
}
private static String getTens(int num) {
String[] z = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
return z[num - 2];
}
private static String getTens(String word) {
String[] z = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
for (int i = 0; i < z.length; i++) {
if (z[i].equals(word)) {
return Integer.toString((i + 2) * 10);
}
}
return null;
}
}
```
注意,为了方便,我把输入的整数和英文单词都当成了字符串处理,通过 `isNumeric()` 方法判断输入的内容是整数还是英文单词。同时,为了避免 `ArrayIndexOutOfBoundsException` 异常,我在 `getTens()` 和 `getDigit()` 方法中添加了对输入错误的处理,如果输入的内容不在预设的数字或单词中,那么返回空值。
阅读全文