ANDROID:将输入的数字转换为单词

nwnhqdif  于 2023-04-10  发布在  Android
关注(0)|答案(5)|浏览(157)

我们的任务是编写一个程序,输入一个最多6位的数字,并将数字转换为单词。123 = 123.我是无线索!然后我发现这个网站http://www.rgagnon.com/javadetails/java-0426.html,但我真的不知道如何将其转换为android.
请帮帮我
下面是我的Main_Activity.xml:

package com.example.torres;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

    final EditText numbers =  (EditText) findViewById(R.id.editText1);
    final EditText results = (EditText) findViewById(R.id.editText2);

    Button btnConvert = (Button) findViewById(R.id.button1);     
    btnConvert.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
         String numberz =numbers.getText().toString();
         try {
             final long number = Long.parseLong(numberz);
             String returnz = Words.convert(number); 
         } catch ( NumberFormatException e) {
             //Toast.makeToast("illegal number or empty number" , toast.long)
         }

                       }  });

        }}

这是我的网站Words.java

package com.example.torres;

import java.text.DecimalFormat;

public class Words  {



      private static final String[] tensNames = {
        "",
        " ten",
        " twenty",
        " thirty",
        " forty",
        " fifty",
        " sixty",
        " seventy",
        " eighty",
        " ninety"
      };

      private static final String[] numNames = {
        "",
        " one",
        " two",
        " three",
        " four",
        " five",
        " six",
        " seven",
        " eight",
        " nine",
        " ten",
        " eleven",
        " twelve",
        " thirteen",
        " fourteen",
        " fifteen",
        " sixteen",
        " seventeen",
        " eighteen",
        " nineteen"
      };

      private Words() {}

    public static String convertLessThanOneThousand(int number) {
        String soFar;

        if (number % 100 < 20){
          soFar = numNames[number % 100];
          number /= 100;
        }
        else {
          soFar = numNames[number % 10];
          number /= 10;

          soFar = tensNames[number % 10] + soFar;
          number /= 10;
        }
        if (number == 0) return soFar;
        return numNames[number] + " hundred" + soFar;
      }

      public static String convert(long number) {
        // 0 to 999 999 999 999
        if (number == 0) { return "zero"; }

        String snumber = Long.toString(number);

        // pad with "0"
        String mask = "000000000000";
        DecimalFormat df = new DecimalFormat(mask);
        snumber = df.format(number);

        // XXXnnnnnnnnn
        int billions = Integer.parseInt(snumber.substring(0,3));
        // nnnXXXnnnnnn
        int millions  = Integer.parseInt(snumber.substring(3,6));
        // nnnnnnXXXnnn
        int hundredThousands = Integer.parseInt(snumber.substring(6,9));
        // nnnnnnnnnXXX
        int thousands = Integer.parseInt(snumber.substring(9,12));

        String tradBillions;
        switch (billions) {
        case 0:
          tradBillions = "";
          break;
        case 1 :
          tradBillions = convertLessThanOneThousand(billions)
          + " billion ";
          break;
        default :
          tradBillions = convertLessThanOneThousand(billions)
          + " billion ";
        }
        String result =  tradBillions;

        String tradMillions;
        switch (millions) {
        case 0:
          tradMillions = "";
          break;
        case 1 :
          tradMillions = convertLessThanOneThousand(millions)
             + " million ";
          break;
        default :
          tradMillions = convertLessThanOneThousand(millions)
             + " million ";
        }
        result =  result + tradMillions;

        String tradHundredThousands;
        switch (hundredThousands) {
        case 0:
          tradHundredThousands = "";
          break;
        case 1 :
          tradHundredThousands = "one thousand ";
          break;
        default :
          tradHundredThousands = convertLessThanOneThousand(hundredThousands)
             + " thousand ";
        }
        result =  result + tradHundredThousands;

        String tradThousand;
        tradThousand = convertLessThanOneThousand(thousands);
        result =  result + tradThousand;

        // remove extra spaces!
        return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");}



      }

现在唯一的问题是什么都没发生LOL

6kkfgxo0

6kkfgxo01#

您可以按照示例链接中的方法为EnglishNumberToWords单独创建类。
在你点击按钮的时候,你只需要

String return_val_in_english =   EnglishNumberToWords.convert(YOUR_NUMBER_TO_CONVERT);

public class EnglishNumberToWords {

private static final String[] tensNames = { "", " ten", " twenty", " thirty", " forty",
        " fifty", " sixty", " seventy", " eighty", " ninety" };

private static final String[] numNames = { "", " one", " two", " three", " four", " five",
        " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen",
        " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" };

private static String convertLessThanOneThousand(int number)
{
    String soFar;

    if (number % 100 < 20)
    {
        soFar = numNames[number % 100];
        number /= 100;
    } else
    {
        soFar = numNames[number % 10];
        number /= 10;

        soFar = tensNames[number % 10] + soFar;
        number /= 10;
    }
    if (number == 0)
        return soFar;
    return numNames[number] + " hundred" + soFar;
}

public static String convert(long number)
{
    // 0 to 999 999 999 999
    if (number == 0)
    {
        return "zero";
    }

    String snumber = Long.toString(number);

    // pad with "0"
    String mask = "000000000000";
    DecimalFormat df = new DecimalFormat(mask);
    snumber = df.format(number);

    // XXXnnnnnnnnn
    int billions = Integer.parseInt(snumber.substring(0, 3));
    // nnnXXXnnnnnn
    int millions = Integer.parseInt(snumber.substring(3, 6));
    // nnnnnnXXXnnn
    int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
    // nnnnnnnnnXXX
    int thousands = Integer.parseInt(snumber.substring(9, 12));

    String tradBillions;
    switch (billions)
    {
        case 0:
            tradBillions = "";
            break;
        case 1:
            tradBillions = convertLessThanOneThousand(billions) + " billion ";
            break;
        default:
            tradBillions = convertLessThanOneThousand(billions) + " billion ";
    }
    String result = tradBillions;

    String tradMillions;
    switch (millions)
    {
        case 0:
            tradMillions = "";
            break;
        case 1:
            tradMillions = convertLessThanOneThousand(millions) + " million ";
            break;
        default:
            tradMillions = convertLessThanOneThousand(millions) + " million ";
    }
    result = result + tradMillions;

    String tradHundredThousands;
    switch (hundredThousands)
    {
        case 0:
            tradHundredThousands = "";
            break;
        case 1:
            tradHundredThousands = "one thousand ";
            break;
        default:
            tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " thousand ";
    }
    result = result + tradHundredThousands;

    String tradThousand;
    tradThousand = convertLessThanOneThousand(thousands);
    result = result + tradThousand;

    // remove extra spaces!
    return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}

}
ubby3x7f

ubby3x7f2#

最重要的是,解决方案工作正常,唯一的问题是不适用于所有语言,因为所有国家都没有相同的规则集将数字转换为单词,所以我们需要为每个国家编写单独的算法,

解决方案

ICU4J是一个国际Unicode组件库,允许许多关于语言翻译的实用程序遵循以下步骤。

*步骤1在应用级gradle中添加ICU 4J,如下图

dependencies {
    implementation group: 'com.ibm.icu', name: 'icu4j', version: '51.1' 
}

*步骤2定义此方法

private String convertIntoWords(Double str,String language,String Country) {
      Locale local = new Locale(language, Country);
      RuleBasedNumberFormat ruleBasedNumberFormat = new RuleBasedNumberFormat(local, RuleBasedNumberFormat.SPELLOUT);
      return ruleBasedNumberFormat.format(str);
}

*步骤3现在可以像下面这样调用这个方法了

double value=165;
String english=convertIntoWords(value,"en","US"); //one hundred and sixty-five
/*Peruvion*/
String Spanish=convertIntoWords(value,"es","PE"); //ciento sesenta y cinco

您可以根据自己的要求更改语言和国家/地区。

xe55xuns

xe55xuns3#

我的答案在这里,因为可以帮助别人...

import android.icu.text.MessageFormat
import java.util.Locale

fun Double.toWords(language: String, country: String): String {
    val formatter = MessageFormat(
        "{0,spellout,currency}", 
        Locale(language, country)
    )
    return formatter.format(arrayOf(this))
}

你可以这样使用它:

import androidx.compose.ui.text.intl.Locale

// ...

(12345678.99).toWords(Locale.current.language, Locale.current.region)

// OR,

(12345678.99).toWords("en", "US") // For static local

此调用将返回字符串
一千二百三十四万五千六百七十八点九九
参考:https://developer.android.com/reference/android/icu/text/MessageFormat

vfh0ocws

vfh0ocws4#

Java类:-

public class NumberToWordsConverter {

        public static final String[] units = {"", "One", "Two", "Three", "Four",
                "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
                "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
                "Eighteen", "Nineteen"};

        public static final String[] tens = {
                "",        // 0
                "",        // 1
                "Twenty",    // 2
                "Thirty",    // 3
                "Forty",    // 4
                "Fifty",    // 5
                "Sixty",    // 6
                "Seventy",    // 7
                "Eighty",    // 8
                "Ninety"    // 9
        };

        public static String convert(final int n) {
            if (n < 0) {
                return "Minus " + convert(-n);
            }

            if (n < 20) {
                return units[n];
            }

            if (n < 100) {
                return tens[n / 10] + ((n % 10 != 0) ? " " : "") + units[n % 10];
            }

            if (n < 1000) {
                return units[n / 100] + " Hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
            }

            if (n < 100000) {
                return convert(n / 1000) + " Thousand" + ((n % 10000 != 0) ? " " : "") + convert(n % 1000);
            }

            if (n < 10000000) {
                return convert(n / 100000) + " Lakh" + ((n % 100000 != 0) ? " " : "") + convert(n % 100000);
            }

            return convert(n / 10000000) + " Crore" + ((n % 10000000 != 0) ? " " : "") + convert(n % 10000000);
        }
    }

**在你的主类中实现。**你可以像下面这样有单独的方法,也可以直接使用而不需要单独的方法。

private String numToWords (int n){ //optional
        NumberToWordsConverter ntw = new NumberToWordsConverter(); // directly implement this
        return ntw.convert(n);
    } //optional
dojqjjoe

dojqjjoe5#

您已经完成了所有工作,只需在文本字段中显示String returnz,如下所示

results.setText(returnz);

相关问题