我需要更简洁的代码
时间: 2024-02-13 15:04:38 浏览: 117
蓝色简洁的网页计算器js代码
好的,以下是更简洁的代码实现:
```
import java.util.*;
public class NumberToEnglish {
private static final String[] DIGITS = {"zero","one","two","three","four","five","six","seven","eight","nine"};
private static final String[] TEENS = {"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
private static final String[] TENS = {"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
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(DIGITS[num]);
} else if (num < 20) {
System.out.println(TEENS[num - 10]);
} else {
System.out.println(TENS[num / 10] + " " + DIGITS[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]));
} else {
System.out.println("输入不正确!");
}
}
}
private static boolean isNumeric(String str) {
return str.matches("\\d+");
}
private static String getDigit(String word) {
for (int i = 0; i < DIGITS.length; i++) {
if (DIGITS[i].equals(word)) {
return Integer.toString(i);
}
}
return null;
}
private static String getTens(String word) {
for (int i = 2; i < TENS.length; i++) {
if (TENS[i].equals(word)) {
return Integer.toString(i * 10);
}
}
return null;
}
}
```
在这个版本中,我将数字转换为英文的数组和常量放在了类的顶部,使代码更加简洁,同时使用了正则表达式判断输入是否为数字,简化了代码。此外,在 `getTens()` 方法中,我从数组的第2个元素开始循环,避免了在数组中添加空值的操作。
阅读全文