单词的Java数字(0-999)

时间:2016-08-15 11:55:31

标签: java arrays numbers

这是我的第一篇文章,我目前正在努力创建一个可以将数字输入转换为各自单词的程序。到目前为止,我的代码写在下面,我似乎无法使数十个正常工作,即21,31,41,51等。

public class NumberToWords {
    public static void main(String[] args) {
       System.out.print("Number: ");
        int value = In.nextInt();
        int onesDigit;
        int tensDigit;
        String [] ones = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
            "eleven", "tweleve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};

        String [] tens = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

        String [] hundreds = {"one hundred", "two hundred", "three hundred", "four hundred", "five hundred", 
            "six hundred", "seven hundred", "eight hundred", "nine hundred" }; 
  while(value != -1)
 {
   if (value < 20)
    {
        String result = ones[value];
        System.out.println("Result " + result);
        value = In.nextInt();
    }
   if (value > 20 && value < 100)
    {
        tensDigit = value%10;
        onesDigit = value/10;
        System.out.print("Result " + ones[onesDigit] + " " + tens[tensDigit]);
        value = In.nextInt();

    }
 }

}    
}

非常感谢任何帮助。

谢谢

1 个答案:

答案 0 :(得分:3)

以下代码不正确:

 tensDigit = value%10;
 onesDigit = value/10;

十位数应为value/10(即如果值为41则为4),而个位数应为value%10(当值除以十时的余数)。

请改用:

  tensDigit = value/10;
  onesDigit = value%10;

此外还有其他要点:

  • 如果值等于20,则不会打印任何内容,因为if-condition都不匹配。

  • 任何可被10整除且大于十(二十,三十等)的值都会打印出“二十零”之类的值。添加另一个if语句来处理value==0的特殊情况,并使数组条目为零,为空字符串。

  • 将print语句中的连接顺序切换为tens[tensDigit] + " " + ones[onesDigit])