我再次尝试解决错误,但无法获得正确的输出我试图从文本字段插入长整数值,但然后字符串生成器正在制造问题我猜。它的问题非常严重,无法在正确的位置做出正确的纠正决定。前3个if语句正在执行而没有错误,问题在于其余的if语句。
public static String numberToWord(final long num) {
// special case to simplify later on
if (num == 0) {
return "zero";
}
// constant number names for each category
// single digits
final String n_1_9[] = new String[]{"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
// unfortunate special cases for ten, eleven, twelve, and teens
final String n_10_19[] = new String[]{"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
// tens
final String n_20_90[] = new String[]{"", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
final String n_100 = "hundred";
final String n_1000 = "thousand";
final String n_100000 = "lakh";
final String n_10000000 = "crore";
// use StringBuilder for efficient modifications
StringBuilder numWord = new StringBuilder();
long n = num;
// append with selective recursion for all our cases
if (n >= 10000000) {
numWord.append(numberToWord(n / 10000000));
numWord.append(' ');
numWord.append(n_10000000);
numWord.append(' ');
n %= 10000000;
}
if (n >= 100000) {
numWord.append(numberToWord(n / 100000));
numWord.append(' ');
numWord.append(n_100000);
numWord.append(' ');
n %= 100000;
}
if (n >= 1000) {
numWord.append(numberToWord(n / 1000));
numWord.append(' ');
numWord.append(n_1000);
numWord.append(' ');
n %= 1000;
}
if (n >= 100) {
numWord.append(n_1_9[n / 100]);
numWord.append(' ');
numWord.append(n_100);
numWord.append(' ');
n %= 100;
}
if (n >= 20) {
numWord.append(n_20_90[(n / 10) - 1]);
numWord.append(' ');
n %= 10;
}
if (n >= 10) {
numWord.append(n_10_19[n - 10]);
}
if (n < 10) {
numWord.append(n_1_9[n]);
}
return numWord.toString().trim();
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
long jml = Long.parseLong(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
答案 0 :(得分:1)
问题在于:
numWord.append(n_1_9[n / 100]);
由于n
是long
,n / 1000
不能用作指标。您需要转换为int
:
numWord.append(n_1_9[(int) n / 100]);
编辑:并为其他指数做同样的事情。
答案 1 :(得分:0)
如果阻止
,则将long转换为最后四个int if (n >= 100) {
numWord.append(n_1_9[(int) (n / 100)]);
numWord.append(' ');
numWord.append(n_100);
numWord.append(' ');
n %= 100;
}
if (n >= 20) {
numWord.append(n_20_90[(int) ((n / 10) - 1)]);
numWord.append(' ');
n %= 10;
}
if (n >= 10) {
numWord.append(n_10_19[(int) (n - 10)]);
}
if (n < 10) {
numWord.append(n_1_9[(int) n]);
}
来自main()的调用方法
String str = numberToWord(100222222222L);
System.out.println("str:: "+ str);