此题等级三,难度不大,主要想练一下map。用map很方便,不用各种if-else判断。在网上找到还有其他做法,用的是Java中的ENUM类ordinal()方法找到英文对应的数字。
另外此题就是字符串处理了,基础不多说
代码:
package Test1;
import java.util.HashMap;
import java.util.Scanner;
public class Test7 {
/**
* by qr jobdu 1010 2014-8-8
*/
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
String num[] = { "zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine" };
for (int i = 0; i < 10; i++) {
map.put(num[i], i);
}
Scanner scan = new Scanner(System.in);
while (true) {
String str = scan.nextLine();
if (str.equals("zero + zero ="))
break;
String equation[] = str.split(" ");
String strch = "";
for (int i = 0; i < equation.length; i++) {
if (!(equation[i].equals("+") || equation[i].equals("=")))
strch += map.get(equation[i]);
else
strch += equation[i];
}
System.out.println(Integer.parseInt(strch.substring(0,
strch.indexOf("+")))
+ Integer.parseInt(strch.substring(strch.indexOf("+") + 1,
strch.indexOf("="))));
}
}
}