【发布时间】:2019-11-30 22:23:10
【问题描述】:
我被分配了一个任务,要编写一个方法,该方法采用小于 1000.00 美元的货币价值,并写出相当于该金额的单词。此金额还需要包括小数点后的部分(本质上是金额的零钱部分)。
即
Enter·check·amount:567.89↵
five·hundred·sixty·seven·and·89/100↵
我看到该主题已被多次讨论,但我似乎找不到任何关于我所请求内容的信息。我是新手(4 周),所以如果我提出错误的问题或以错误的方式说明我所做的事情,请原谅我。我可以用文字输出金额(从我的结果中可以看出),但我相信我遇到的问题在于用户输入了 Double 并且我的代码不包括任何请求
//program to write the word equivalent of a check amount
import java.util.Scanner;
public class CheckToWord {
public static void main(String[] args) { // main method
double number = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the check amount:"); // prompt user to enter check amount
number = scanner.nextDouble();
if (number == 0) {
System.out.print("Zero");
} else {
System.out.print("" + moneyWord((int) number)); // output amount in words
}
}
private static String moneyWord(int number) {
String words = ""; // variable to hold string representation of number
String onesArray[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
String tensArray[] = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty",
"ninety" };
if (number < 0) { // convert the number to a string
String numberStr = "" + number;
numberStr = numberStr.substring(1); // remove minus before the number
return "minus " + moneyWord((int) Double.parseDouble(numberStr)); // add minus before the number and convert
// the rest of number
}
if ((number / 1000) > 0) { // check if number is divisible by 1 thousand
words += moneyWord(number / 1000) + " thousand ";
number %= 1000;
}
if ((number / 100) > 0) { // check if number is divisible by a hundred
words += moneyWord(number / 100) + " hundred ";
number %= 100;
}
if (number < 20) { // check if number is within the teens
words += onesArray[number]; // get the appropriate value from ones array
} else {
words += tensArray[number / 10]; // get the appropriate value from tens array
if ((number % 10) > 0) {
words += "-" + onesArray[number % 10];
}
}
return words;
}
}
结果
Please enter the check amount:
1523.23
one thousand five hundred twenty-three
【问题讨论】:
-
好的,所以如果我理解正确,你有一个编译错误。发布包含错误的代码。发布来自编译器的准确和完整的错误消息。告诉错误消息指的是哪一行代码。另外,如果你想要一个 int,请解释为什么你要求一个 double。如果目标是转换一个小数,为什么你需要一个 int。
-
1523.23 是无效输入,因为该值应小于 $1000.00
-
@MartínZaragoza 感谢您的快速回复。我现在想回去复制错误,以便我可以发布它们。我知道我的输入超过了 1000.00 美元,但我想我可能需要说明用户只输入了不到 1000 美元的金额。我还将尝试您发布到我的代码中的输入。请继续关注。
-
太棒了。进展如何?对你有用吗?
-
@JBNizet 如果我将 moneyWord 方法中的 int 数字更改为 Double,第 45、48 和 50 行中的数字会显示“类型不匹配:无法从 Double 转换为 Int”。但是在查看了 Martin 发布的内容后,问题不止于此。因为我需要修改代码的所有 3 种方法以及 If 语句。正如我之前提到的,有些事情我们还没有涉及,我试图自己弄清楚,即数组和解析。再次感谢您的帮助。
标签: java arrays string currency