Change Number to English By Reading rule of money

In the partime,  a simle program attracted my attention whose content is to change number to english by reading rule of money.It took about one hour to deal with this question. Now the source was shared with everyone.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class Number {

	public static final String[] ENGLISH_NUMBER = { "zero", "one", "two",
			"three", "four", "five", "six", "seven", "eight", "nine" };

	public static final String[] ENGLISH_DOCNUMBER = { "ten", "twenty",
			"thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" };

	public static final String[] ENGLISH_UNIT = { "hundred", "thousand",
			"million", "billion" };

	public static final StringBuilder sb = new StringBuilder(0);

	public static void parse() {
		sb.setLength(0);
		readFile("in.txt");
		writeFile(sb.toString(), "out.txt");

		return;
	}

	public static void readFile(String fileName) {

		File file = new File(fileName);
		FileInputStream fis = null;
		BufferedReader br = null;
		try {
			fis = new FileInputStream(file);
			br = new BufferedReader(new InputStreamReader(fis, "gb2312"));
			String temp = "";
			while ((temp = br.readLine()) != null) {
				sb.append(temp).append("=").append(formate(parseTotal(temp)))
						.append("\r\n");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void writeFile(String result, String fileName) {
		File f = new File(fileName);
		FileWriter fw = null;
		BufferedWriter bw = null;

		try {
			if (!f.exists()) {
				f.createNewFile();
			}
			fw = new FileWriter(f);
			bw = new BufferedWriter(fw);
			bw.write(result);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bw != null) {
					bw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String parseLine(String str) {
		String result = "";
		if (isLegel(str)) {
			while (str.length() > 0) {
				int length = str.length();
				switch (length) {
				case 1:
					result += ENGLISH_NUMBER[Integer.valueOf(str)];
					str = "";
					break;
				case 2:
					char[] strArr = str.toCharArray();
					if (Character.getNumericValue(strArr[0]) == 0) {
						result += ("zero" + ENGLISH_NUMBER[Character
								.getNumericValue(strArr[1])]);
					} else {
						result += (ENGLISH_DOCNUMBER[Character
								.getNumericValue(strArr[0]) - 1]
								+ " " + ENGLISH_NUMBER[Character
								.getNumericValue(strArr[1])]);
					}
					str = "";
					break;
				case 3:
					char[] strArr1 = str.toCharArray();
					result += ENGLISH_NUMBER[Character
							.getNumericValue(strArr1[0])]
							+ " " + ENGLISH_UNIT[0] + " and ";
					str = str.substring(1);
					break;
				case 4:
					char[] strArr2 = str.toCharArray();
					result += ENGLISH_NUMBER[Character
							.getNumericValue(strArr2[0])]
							+ " " + ENGLISH_UNIT[1] + " and ";
					str = str.substring(1);
					break;
				default:
					break;
				}
			}
		} else {
			result = "error";
		}

		if (result.indexOf("zero") != -1) {
			result = result.replace("zero", "");
		}
		if (result.trim().endsWith("and")) {
			result = result.substring(0, result.lastIndexOf("and"));
		}
		return result.trim();
	}

	public static String parseTotal(String str) {
		String result = "";
		while (str.length() > 0) {
			if(str.indexOf("error") != -1)
			{
				result = "error";
				break;
			}
			if (str.length() <= 3) {
				result += parseLine(str);
				break;
			} else if (str.length() > 3 && str.length() < 7) {
				String highStr = str.substring(0, str.length() - 3);
				String lowStr = str.substring(str.length() - 3);
				result += (parseLine(highStr) + " " + ENGLISH_UNIT[1] + " " + parseLine(lowStr));
				break;
			} else if (str.length() >= 7 && str.length() <= 9) {
				String highStr = str.substring(0, str.length() - 6);
				result += (parseLine(highStr) + " " + ENGLISH_UNIT[2] + " ");
				str = str.substring(str.length() - 5);
			} else if (str.length() > 9 && str.length() <= 10) {
				String highStr = str.substring(0, str.length() - 9);
				result = parseLine(highStr) + " " + ENGLISH_UNIT[3] + " ";
				str = str.substring(str.length() - 8);
			}
		}

		// 111,112,112
		return result.toLowerCase();
	}

	public static boolean isLegel(String str) {
		boolean flag = true;
		if (str.length() >= 10) {
			flag = false;
		} else if (str.indexOf(".") != -1) {
			flag = false;
		} else {
			try {
				int number = Integer.parseInt(str);
				if (number <= 0) {
					flag = false;
				}
			} catch (NumberFormatException e) {
				flag = false;
			}
		}

		return flag;
	}

	public static String formate(String str) {
		str = str.replace("ten one", "eleven");
		str = str.replace("ten two", "twelve");
		str = str.replace("ten three", "thirteen");
		str = str.replace("ten four", "fourteen");
		str = str.replace("ten five", "fifteen");
		str = str.replace("ten six", "sixteen");
		str = str.replace("ten seven", "seventeen");
		str = str.replace("ten eight", "eighteen");
		str = str.replace("ten nine", "nineteen");

		return str;
	}

	public static void main(String[] args) {
		System.out.println(formate(parseTotal("11632")));
		System.out.println(formate(parseTotal("123")));
	}
}

The output is:

eleven thousand six hundred and thirty two

one hundred and twenty three

Change Number to English By Reading rule of money,布布扣,bubuko.com

时间: 2024-10-12 01:14:26

Change Number to English By Reading rule of money的相关文章

How to change 2011 x3 series F25 CIC from English to German

This is a conversation between a F25 owner and a professional technician talking about F25 CIC language change Purpose: To change 2011 x3 series F25 CIC from English to German. A: I've got a 2011 x3 series F25 and have just retrofitted a CIC into it

LightOJ 1231 Coin Change (I) (背包计数模板题)

1231 - Coin Change (I) PDF (English) Statistics Forum Time Limit: 1 second(s) Memory Limit: 32 MB In a strange shop there are n types of coins of valueA1, A2 ... An.C1, C2,... Cn denote the number of coins of valueA1, A2... An respectively. You have

Morning Reading Collection

w5d6 Hey, guys, these days I started to  do some English morning reading. I just read out some nice English sentences or sayings. Today, I would share with you some of those good ones here in the blog. And hope you guys could enjoy it. Thank you! ===

modify与change的区别

对mysql的表的表结构进行修改时,有用到change,modify两个,它们都有"改变"的意思,那它们在功能上有什么区别了?做个试验比较下 1.字段重命名: 1)change mysql> alter table t1 change number id char(2); Query OK, 0 rows affected (0.08 sec) Records: 0  Duplicates: 0  Warnings: 0 2)modify mysql> alter tabl

FCC算法题--Exact Change

题目: 设计一个收银程序 checkCashRegister() ,其把购买价格(price)作为第一个参数 , 付款金额 (cash)作为第二个参数, 和收银机中零钱 (cid) 作为第三个参数. cid 是一个二维数组,存着当前可用的找零. 当收银机中的钱不够找零时返回字符串 "Insufficient Funds". 如果正好则返回字符串 "Closed". 否则, 返回应找回的零钱列表,且由大到小存在二维数组中. 当你遇到困难的时候,记得查看错误提示.阅读文

English trip -- VC(情景课)1 C What&#39;s your name?

Grammar focus 语法点 What's your name? What's his name? What her name? My name is Angela. His name is Kevin. Her name is Julia. Practice 练习 Read and circle your  his  her                 Chin    Alima   Vincent example: What's your name ? My name is Nan

[Lintcode]184. Largest Number/[Leetcode]179. Largest Number

184. Largest Number/179. Largest Number 本题难度: Medium Topic: Greedy Description Largest Number 中文English Given a list of non negative integers, arrange them such that they form the largest number. Example Given [1, 20, 23, 4, 8], the largest formed nu

(转)Understanding C parsers generated by GNU Bison

原文链接:https://www.cs.uic.edu/~spopuri/cparser.html Satya Kiran PopuriGraduate StudentUniversity of Illinois at ChicagoChicago, IL 60607spopur2 [at] uic [dot] eduWed Sep 13 12:24:25 CDT 2006 Table of Contents Introduction Prerequisites The LR Parser An

Make命令完全详解教程

无论是在Linux还是在Unix环境中,make都是一个非常重要的编译命令.不管是自己进行项目开发还是安装应用软件,我们都经常要用到make或make install.利用make工具,我们可以将大型的开发项目分解成为多个更易于管理的模块,对于一个包括几百个源文件的应用程序,使用make和makefile工具就可以简洁明快地理顺各个源文件之间纷繁复杂的相互关系.而且如此多的源文件,如果每次都要键入gcc命令进行编译的话,那对程序员来说简直就是一场灾难.而make工具则可自动完成编译工作,并且可以