大家好,我正在完成一个在线练习,我必须创建一个程序来读取几段文本。所有数字(以文本形式编写)必须相加,并在末尾显示总和。
如果你们不介意回答,我有几个问题,因为我对此进行了相当多的研究。
这只是使用的文本示例:
例如,请记住,您正站在十二点钟的站台上,有五辆火车在九个轨道上每小时运行一次。一列火车的速度可以达到每小时两百英里。亿万中的一...
我正在使用 StringTokenizer,因此每个单词都是单独读取的。
通过研究,我学会了创建表示每个单词的数组(请参见代码示例),这样单词就可以很容易地表示为整数。虽然我也为每个数字创建了变量,但这可能不是必需的,尽管我不明白 Java 如何将一个单词表示为它的有效数字。(再次请参阅代码)。
虽然我最大的问题是我将如何使用循环组合像 281 = 281 这样的单词。
任何建议将不胜感激,我知道这段代码远非完美,因为我正在继续通过在线材料和书籍学习。
class wordsToNumberAdder
{
public static void main()
{
String str = "Just remember that you're standing on a platform at twelve o'clock and there are
five trains that run every hour on nine tracks. A train can go as fast as two hundred miles
an hour. One of millions of billions... ";
StringTokenizer st = new StringTokenizer(str);
String[] digits = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
String[] tens = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
String[] teens = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
String[] power = {"hundred","thousand","million","billion"};
int one = 1, two = 2, three = 3, four = 4, five = 5, six = 6, seven = 7, eight = 8, nine = 9;
int twenty = 20, thirty = 30, forty = 40, fifty = 50, sixty = 60, seventy = 70, eighty = 80, ninety = 90;
int ten = 10, eleven = 11, twelve = 12, thirteen = 13, forteen = 14, fifthteen = 15, sixteen = 16;
int eighteen = 18, nineteen = 19, thirty = 30, hundred = 100, thousand = 1000;
long billion = 1000000000;
double result = 0;
double group = 0;
while (set.hasMoreTokens()) {
String word = set.nextToken();
for (int x = 0; x < power.length; i += 3) {
if (word.equals(power[i])) {
group = group * Math.pow(10, i);
result = result + group;
group = 0;
}
}