gpt4 book ai didi

java - 需要帮助在 Java 中将数字转换为单词

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:58 26 4
gpt4 key购买 nike

我正在开发一个将数字转换为单词的程序,但我在使用 Numbers 类中的 toString() 方法时遇到问题。所有的方法都给了我,我可以实现;因此,我无法删除其中任何一个...

数量:4564 --> 四千五百六十四

这是代码数字类

package numberstowords;

import java.util.*;

public class Numbers {

//array containing single digits words numbers:0-9
private final String[] SINGLE_DIGITS_WORDS;

//array containing special words words eg:10-19
private final String[] TEEN_DIGITS_WORDS;

//array containing tens words numbers:20-90
private final String[] TEN_DIGITS_WORDS;

private int value, //number to be converted to words
one, //number to store digits
ten, //number to store tens
hundred, //number to store hundred
thousand;//number to store thousand

private String strOut;

//conscructor: Initializing value and arrays
public Numbers(int n)


//getting single digit number
private int getOnes()
{
one = value % 10;
return one;
}

//getting tens numbers
private int getTens()
{
ten = value % 100;
ten /= 10;
return ten;
}

//getting hundreds numbers
private int getHundreds()
{
hundred = value % 1000;
hundred /= 100;
return hundred;
}

//getting thousands numbers
private int getThousands()
{
thousand = value % 10000;
thousand /= 1000;
return thousand;
}

//converting and returning string of ones
private String digitsToString(int one)
{
return SINGLE_DIGITS_WORDS[one];
}

//converting and returning strings of tens and teens
private String tensAndOnesToString(int ten, int one)
{
if(ten == 1)//if number is a teen return, else return tens
{
return TEEN_DIGITS_WORDS[one];
}
return TEN_DIGITS_WORDS[ten-2];
}

//converting and returning strings of hundreds
private String hundredsToString(int hundred)
{
return digitsToString(hundred) + " hundred";
}

private String thousandsToString(int thousand)
{
return digitsToString(thousand) + " thousand";
}

最佳答案

根据您的评论,问题是您获得 11-19 之间数字的 ones 输出。

查看您的 tensAndOnesToString() 方法,它检查是否 ten == 1,以识别 teens 数字。那么,为什么不在 if(d4 != 0) 行中进行类似的检查,

    if(d4 != 0 && d3 != 1) // CHANGED THIS LINE
{
if(strOut.equals(""))
strOut = digitsToString(one);
else
{
strOut = strOut +" "+ digitsToString(one);
}
}

现在,如果它 (d4) 不是 0,并且 (d3) 不是 1,它只会输出 one 数字。

关于java - 需要帮助在 Java 中将数字转换为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10590115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com