Related
public class NumberWords {
public String toWords(int number) {
String result = "";
if (number == -1) {
result = "Number out of range";
}
if (number >= 0 && number <= 999) {
if (number == 0) {
System.out.println("NUMBER AFTER CONVERSION:\tZERO");
} else {
System.out.print("NUMBER AFTER CONVERSION:\t");
numberToWord(((number / 100) % 10), " HUNDRED");
numberToWord((number % 100), " ");
}
}else if(number >= 1000){
System.out.println("Number not in range");
}
if (number == 0) {
System.exit(number);
}
return result.trim();
}
public static void numberToWord(int num, String val) {
String ones[] = {" ", " ONE", " TWO", " THREE", " FOUR", " FIVE", " SIX", " SEVEN", " EIGHT", " NINE", " TEN", " ELEVEN", " TWELVE", " THIRTEEN", " FOURTEEN", " FIFTEEN", " SIXTEEN", " SEVENTEEN", " EIGHTEEN", " NINETEEN"
};
String tens[] = {" ", " ", " TWENTY", " THIRTY", " FOURTY", " FIFTY", " SIXTY", " SEVENTY", " EIGHTY", " NINETY"};
if (num > 19) {
System.out.print(tens[num / 10] + " " + ones[num % 10]);
} else {
System.out.print(ones[num]);
}
if (num > 0) {
System.out.print(val);
}
}
}
public class NumberWordsApplication {
private final NumberWords numberWords;
private final BufferedReader reader;
public NumberWordsApplication() {
numberWords = new NumberWords();
reader = new BufferedReader(new InputStreamReader(System.in));
}
public void execute() {
while (true) {
try {
System.out.print("\nPlease type a number between 1 and 999 OR (0 to exit) : ");
String value = reader.readLine();
int number = Integer.parseInt(value);
String toWords = numberWords.toWords(number);
} catch (NumberFormatException | IOException e) {
System.out.println("Invalid number");
}
}
}
public static void main(String[] args) {
new NumberWordsApplication().execute();
}
}
This is main class for generate number to word eg 57 then output should be "Fifty Seven"
I want to generate test cases for class NumberWords i have got stuck
Develop the numbers to words application using TDD
Implement the main application to read numbers from the keyboard
and print out the values
On the server navigate to the Numbers
project
Run ant to build the project. The build will fail if the
unit tests fail.
~/ant/bin/ant dist
The results of the unit
tests are in the report directory which got created Run the
application and try it out
java –j Numbers.jar
Since this is a (homework?) question about Test-Driven Development, the very first steps would be to:
Create a very simple test case that checks that the number 1 is mapped to "ONE"
Create a very simple implementation that just returns "ONE" when the input is 1.
Create a built script (using ant if you must) to run this test.
Once you have this up and running you can gradually add more test cases, until your class (which will be a simplified version of NumberWords) can convert any input.
To keep the application testable it is best to abstain from using System.exit(), and to minimize code included in a while(true). This is easy to do for the given assignment.
It looks like you have tried to apply TDD in the wrong order, doing test-last instead of test-first development.
I am currently working on a project where I read in a CSV file that contains a list of Pokemon, as well as their traits. I am trying to run a battle simulator that randomly pairs up these Pokemon with each other and compares their combatScore, which is a result of a simple calculation using their traits such as speed, attack, defense, etc. I read in all of the Pokemon from the CSV file into an ArrayList of type Pokemon. Now, I want to randomly pair them up with each other and compare their combatScore; whoever has the higher score moves on to the next round, and the loser is placed into another ArrayList of defeated Pokemon. However, I do not know how to randomly pair up the Pokemon. Here is my code of the main class so far:
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
public class assign1 {
public static void main(String[] args) throws IOException {
String csvFile = args[0]; //path to CSV file
String writeFile = args[1]; //name of output file that contains list of Pokemon and their traits
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Pokemon> population = new ArrayList<Pokemon>();
FileWriter fileWriter = new FileWriter(writeFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
try {
br = new BufferedReader(new FileReader(csvFile));
String headerLine = br.readLine(); // used to read first line of CSV file that contains headers
while ((line = br.readLine()) != null) {
Pokemon creature = new Pokemon();
// use comma as separator
String[] pokemon = line.split(cvsSplitBy);
creature.setId(pokemon[0]);
creature.setName(pokemon[1]);
creature.setType1(pokemon[2]);
creature.setType2(pokemon[3]);
creature.setTotal(pokemon[4]);
creature.setHp(Integer.parseInt(pokemon[5]));
creature.setAttack(Integer.parseInt(pokemon[6]));
creature.setDefense(Integer.parseInt(pokemon[7]));
creature.setSpAtk(Integer.parseInt(pokemon[8]));
creature.setSpDef(Integer.parseInt(pokemon[9]));
creature.setSpeed(Integer.parseInt(pokemon[10]));
creature.setGeneration(Integer.parseInt(pokemon[11]));
creature.setLegendary(Boolean.parseBoolean(pokemon[12]));
creature.getCombatScore();
// Adds individual Pokemon to the population ArrayList
population.add(creature);
// Writes to pokemon.txt the list of creatures
bufferedWriter.write(creature.getId() + ". "
+ "Name: " + creature.getName() + ": "
+ "Type 1: " + creature.getType1() + ", "
+ "Type 2: " + creature.getType2() + ", "
+ "Total: " + creature.getTotal() + ", "
+ "HP: " + creature.getHp() + ", "
+ "Attack: " + creature.getAttack() + ", "
+ "Defense: " + creature.getDefense() + ", "
+ "Special Attack: " + creature.getSpAtk() + ", "
+ "Special Defense: " + creature.getSpDef() + ", "
+ "Speed: " + creature.getSpeed() + ", "
+ "Generation: " + creature.getGeneration() + ", "
+ "Legendary? " + creature.isLegendary() + ", "
+ "Score: " + creature.getCombatScore());
bufferedWriter.newLine();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
bufferedWriter.close();
}
}
And here is the code for my Pokemon class:
public class Pokemon {
String id;
String name;
String type1;
String type2;
String total;
int hp;
int attack;
int defense;
int spAtk;
int spDef;
int speed;
int generation;
boolean legendary;
public Pokemon() {}
public String getId () {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType1() {
return type1;
}
public void setType1(String type1) {
this.type1 = type1;
}
public String getType2() {
return type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getSpAtk() {
return spAtk;
}
public void setSpAtk(int spAtk) {
this.spAtk = spAtk;
}
public int getSpDef() {
return spDef;
}
public void setSpDef(int spDef) {
this.spDef = spDef;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getGeneration() {
return generation;
}
public void setGeneration(int generation) {
this.generation = generation;
}
public boolean isLegendary() {
return legendary;
}
public void setLegendary(boolean legendary) {
this.legendary = legendary;
}
public int getCombatScore() {
return (speed/2) * (attack + (spAtk/2)) + (defense + (spDef/2));
}
#Override
public String toString() {
return "Name: " + this.getName()
+ ", Type 1: " + this.getType1()
+ ", Type 2: " + this.getType2()
+ ", Total: " + this.getTotal()
+ ", HP: " + this.getHp()
+ ", Attack: " + this.getAttack()
+ ", Defense: " + this.getDefense()
+ ", Sp. Attack: " + this.getSpAtk()
+ ", Sp. Defense: " + this.getSpDef()
+ ", Generation: " + this.getGeneration()
+ ", Legnedary: " + this.isLegendary()
+ ", Score: " + this.getCombatScore();
}
}
I only want to compare their combatScore values to each other. Any help/suggestions would be much appreciated.
What come to my mind is this. You pick one random item (pokemon) from array list. Remove it from array list. Then you pick one random item again and remove it. Now you have a pair of items. Repeat above step for remaining items in array list until no more items available.
Or you can shuffle whole array list first and then pick item i and item i+1 as pair for i=0,2,4,6,...
Collections.shuffle(pokemonsArrayList);
for (int i=0; i< pokemonsArrayList.size(); i+=2) {
pokemon1 = pokemonsArrayList.get(i);
pokemon2 = pokemonsArrayList.get(i+1);
}
Just make sure that number of elements in ArrayList is even. Otherwise code above will throw exception index out of bound
Since every element in an ArrayList has an index, you can just get a random element from it by calling
Pokemon pokemon1;
Pokemon pokemon2;
pokemon1 = arrayList.get(Math.random()*arrayList.size());
do {
pokemon2 = arrayList.get(Math.random()*arrayList.size());
} while(pokemon1.getId() == pokemon2.getId());
then compare the Pokémon you got out of List1 with the one you got from List2.
You can then of course remove the Pokémon from the List if you wish.
Hope that helps you out!
This question already has answers here:
How to convert number to words in java
(31 answers)
Closed 8 years ago.
When this was assign to me I already had something in mind on how to do it, but that "Thing" that I was thinking is to do it manually 1-1000 like so:
import.java.io.*
public static void main(String[] args) throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int num;
System.out.println("Enter Numbers to convert: ");
num=Integer.parseInt(in.readLine());
if (num==1)
{
System.out.println("one");
}
else if(num==2)
{
System.out.println("two");
}
else if(num==3)
{
System.out.println("three");
}
\*and so on up to 1000*\
Please help i dont want to do that ! im just a noob programmer :(
Got it from here and modified it according to your needs. Credit goes fully to the original owner of this code.
import java.text.DecimalFormat;
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 EnglishNumberToWords() {}
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", " ");
}
/**
* testing
* #param args
*/
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number");
int i = scanner.nextInt();
System.out.println("*** " + EnglishNumberToWords.convert(i));
}
catch(Exception e) {
}
}
}
A more simple one :
public class ConvertNumberToWords {
final private static String[] units = {"Zero","One","Two","Three","Four",
"Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen",
"Sixteen","Seventeen","Eighteen","Nineteen"};
final private static String[] tens = {"","","Twenty","Thirty","Forty","Fifty",
"Sixty","Seventy","Eighty","Ninety"};
public static String convert(Integer i) {
if( i < 20) return units[i];
if( i < 100) return tens[i/10] + ((i % 10 > 0)? " " + convert(i % 10):"");
if( i < 1000) return units[i/100] + " Hundred" + ((i % 100 > 0)?" and " + convert(i % 100):"");
if( i < 1000000) return convert(i / 1000) + " Thousand " + ((i % 1000 > 0)? " " + convert(i % 1000):"") ;
return convert(i / 1000000) + " Million " + ((i % 1000000 > 0)? " " + convert(i % 1000000):"") ;
}
public static void main(String[]args){
for(int i=1;i<1000;i++){
System.out.println(i+" \t "+convert(i));
}
}
}
you have to made numberArray upto thousand count if you want to print string against each read number :P
public static void main(String[] args) throws IOException
{
public static final String[] numberArray = new String[] {
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String number = in.readLine();
int num = 0;
while(num!=1000){
if (num == Integer.parseInt(number)) {
System.out.println(numberArray[num]);
}
num++;
}
}
Our assignment states that we write a program that will input a number up to 6 digits and will convert the numbers into words.. ex: 123 = one hundred twenty three. I AM CLUELESS! Then I found this site http://www.rgagnon.com/javadetails/java-0426.html
but I don't really understand how to convert it into android.
please help me..please.
here is my 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)
}
} });
}}
and here is my 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", " ");}
}
The only problem now is that nothing happens lol
You can make separate class for EnglishNumberToWords as in the example link.
and in your button click you have to just call
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", " ");
}
}
Above all the solution is working fine, Only problem is that this is not working for all language because all country is not having the same set of rules to convert a number into word so we need to write a separate algorithm for each country,
Solution
ICU4J is an international Unicode component library that is allowed so many utilities regarding language translation follow below steps.
Step 1 Add ICU4J in your app level gradle like below
dependencies {
implementation group: 'com.ibm.icu', name: 'icu4j', version: '51.1'
}
Step 2 Define this method
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);
}
Step 3
Now you can call this method like below
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
You can change language and country based on your requirements.
Enjoy
Posting my answer here because can be helpful to someone else...
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))
}
and you can use it like 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
This call will return the string
twelve million three hundred forty-five thousand six hundred seventy-eight point nine nine
Reference: https://developer.android.com/reference/android/icu/text/MessageFormat
Java Class for that :-
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);
}
}
Implementation in your main class.
You can have separate method like the follwing or you can directly use without separate method.
private String numToWords (int n){ //optional
NumberToWordsConverter ntw = new NumberToWordsConverter(); // directly implement this
return ntw.convert(n);
} //optional
You have done all the work just display String returnz in a text field like this
results.setText(returnz);
Anyone know of a java library that can take very large spelled numbers and convert them into digits? It'd be nice if it could do decimal places as well. Example.. Ten to 10
Hmm why not try your own? Here are 2 samples to start you off:
import java.util.*;
public class NumToWords {
String string;
String st1[] = { "", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", };
String st2[] = { "hundred", "thousand", "lakh", "crore" };
String st3[] = { "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "ninteen", };
String st4[] = { "twenty", "thirty", "fourty", "fifty", "sixty", "seventy",
"eighty", "ninty" };
public String convert(int number) {
int n = 1;
int word;
string = "";
while (number != 0) {
switch (n) {
case 1:
word = number % 100;
pass(word);
if (number > 100 && number % 100 != 0) {
show("and ");
}
number /= 100;
break;
case 2:
word = number % 10;
if (word != 0) {
show(" ");
show(st2[0]);
show(" ");
pass(word);
}
number /= 10;
break;
case 3:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[1]);
show(" ");
pass(word);
}
number /= 100;
break;
case 4:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[2]);
show(" ");
pass(word);
}
number /= 100;
break;
case 5:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[3]);
show(" ");
pass(word);
}
number /= 100;
break;
}
n++;
}
return string;
}
public void pass(int number) {
int word, q;
if (number < 10) {
show(st1[number]);
}
if (number > 9 && number < 20) {
show(st3[number - 10]);
}
if (number > 19) {
word = number % 10;
if (word == 0) {
q = number / 10;
show(st4[q - 2]);
} else {
q = number / 10;
show(st1[word]);
show(" ");
show(st4[q - 2]);
}
}
}
public void show(String s) {
String st;
st = string;
string = s;
string += st;
}
public static void main(String[] args) {
NumToWords w = new NumToWords();
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
int num = input.nextInt();
String inwords = w.convert(num);
System.out.println(inwords);
}
}
and this:
class constNumtoLetter
{
String[] unitdo ={"", " One", " Two", " Three", " Four", " Five",
" Six", " Seven", " Eight", " Nine", " Ten", " Eleven", " Twelve",
" Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen",
" Eighteen", " Nineteen"};
String[] tens = {"", "Ten", " Twenty", " Thirty", " Forty", " Fifty",
" Sixty", " Seventy", " Eighty"," Ninety"};
String[] digit = {"", " Hundred", " Thousand", " Lakh", " Crore"};
int r;
//Count the number of digits in the input number
int numberCount(int num)
{
int cnt=0;
while (num>0)
{
r = num%10;
cnt++;
num = num / 10;
}
return cnt;
}
//Function for Conversion of two digit
String twonum(int numq)
{
int numr, nq;
String ltr=\"";
nq = numq / 10;
numr = numq % 10;
if (numq>19)
{
ltr=ltr+tens[nq]+unitdo[numr];
}
else
{
ltr = ltr+unitdo[numq];
}
return ltr;
}
//Function for Conversion of three digit
String threenum(int numq)
{
int numr, nq;
String ltr = "";
nq = numq / 100;
numr = numq % 100;
if (numr == 0)
{
ltr = ltr + unitdo[nq]+digit[1];
}
else
{
ltr = ltr +unitdo[nq]+digit[1]+" and"+twonum(numr);
}
return ltr;
}
}
class originalNumToLetter
{
public static void main(String[] args) throws Exception
{
//Defining variables q is quotient, r is remainder
int len, q=0, r=0;
String ltr = " ";
String Str = "Rupees";
constNumtoLetter n = new constNumtoLetter();
int num = Integer.parseInt(args[0]);
if (num <= 0) System.out.println(\"Zero or Negative number not for conversion");
while (num>0)
{
len = n.numberCount(num);
//Take the length of the number and do letter conversion
switch (len)
{
case 8:
q=num/10000000;
r=num%10000000;
ltr = n.twonum(q);
Str = Str+ltr+n.digit[4];
num = r;
break;
case 7:
case 6:
q=num/100000;
r=num%100000;
ltr = n.twonum(q);
Str = Str+ltr+n.digit[3];
num = r;
break;
case 5:
case 4:
q=num/1000;
r=num%1000;
ltr = n.twonum(q);
Str= Str+ltr+n.digit[2];
num = r;
break;
case 3:
if (len == 3)
r = num;
ltr = n.threenum(r);
Str = Str + ltr;
num = 0;
break;
case 2:
ltr = n.twonum(num);
Str = Str + ltr;
num=0;
break;
case 1:
Str = Str + n.unitdo[num];
num=0;
break;
default:
num=0;
System.out.println(\"Exceeding Crore....No conversion");
System.exit(1);
}
if (num==0)
System.out.println(Str+\" Only");
}
}
}
EDIT:
This sample will convert up to the billions it seems:
import java.text.DecimalFormat;
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", " ");
}
/**
* testing
* #param args
*/
public static void main(String[] args) {
System.out.println("*** " + EnglishNumberToWords.convert(0));
System.out.println("*** " + EnglishNumberToWords.convert(1));
System.out.println("*** " + EnglishNumberToWords.convert(16));
System.out.println("*** " + EnglishNumberToWords.convert(100));
System.out.println("*** " + EnglishNumberToWords.convert(118));
System.out.println("*** " + EnglishNumberToWords.convert(200));
System.out.println("*** " + EnglishNumberToWords.convert(219));
System.out.println("*** " + EnglishNumberToWords.convert(800));
System.out.println("*** " + EnglishNumberToWords.convert(801));
System.out.println("*** " + EnglishNumberToWords.convert(1316));
System.out.println("*** " + EnglishNumberToWords.convert(1000000));
System.out.println("*** " + EnglishNumberToWords.convert(2000000));
System.out.println("*** " + EnglishNumberToWords.convert(3000200));
System.out.println("*** " + EnglishNumberToWords.convert(700000));
System.out.println("*** " + EnglishNumberToWords.convert(9000000));
System.out.println("*** " + EnglishNumberToWords.convert(9001000));
System.out.println("*** " + EnglishNumberToWords.convert(123456789));
System.out.println("*** " + EnglishNumberToWords.convert(2147483647));
System.out.println("*** " + EnglishNumberToWords.convert(3000000010L));
/*
*** zero
*** one
*** sixteen
*** one hundred
*** one hundred eighteen
*** two hundred
*** two hundred nineteen
*** eight hundred
*** eight hundred one
*** one thousand three hundred sixteen
*** one million
*** two millions
*** three millions two hundred
*** seven hundred thousand
*** nine millions
*** nine millions one thousand
*** one hundred twenty three millions four hundred
** fifty six thousand seven hundred eighty nine
*** two billion one hundred forty seven millions
** four hundred eighty three thousand six hundred forty seven
*** three billion ten
**/
}
}
References:
http://www.roseindia.net/tutorial/java/core/convertNumberToWords.html
http://www.java-samples.com/showtutorial.php?tutorialid=1156
http://www.rgagnon.com/javadetails/java-0426.html
Surprisingly it seems that there is no Java library yet which solves this task. Since I found the Python solution in the question comment elegant I converted it to Java:
Text2Digit.java
public class Text2Digit {
final static String[] units = { "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen" };
final static String[] tens = { "", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
final static String[] scales = { "hundred", "thousand", "million",
"billion", "trillion" };
final static Map<String, ScaleIncrement> numWords = new HashMap<>();
static {
numWords.put("and", ScaleIncrement.valueOf(1, 0));
for (int i = 0; i < units.length; i++)
numWords.put(units[i], ScaleIncrement.valueOf(1, i));
for (int i = 0; i < tens.length; i++)
numWords.put(tens[i], ScaleIncrement.valueOf(1, i * 10));
for (int i = 0; i < scales.length; i++) {
int exponent = (i * 3 == 0) ? 2 : i * 3;
numWords.put(scales[i],
ScaleIncrement.valueOf((int) Math.pow(10, exponent), 0));
}
}
public static long convert(String text) {
long current = 0;
long result = 0;
for (String word : text.split(" ")) {
if (!numWords.containsKey(word))
throw new RuntimeException("Illegal word:" + word);
long scale = numWords.get(word).scale;
long increment = numWords.get(word).increment;
current = current * scale + increment;
if (scale > 100) {
result += current;
current = 0;
}
}
return result + current;
}
}
ScaleIncrement.java
public class ScaleIncrement {
long scale;
long increment;
private ScaleIncrement() {}
public static ScaleIncrement valueOf(long scale, long increment) {
ScaleIncrement result = new ScaleIncrement();
result.scale = scale;
result.increment = increment;
return result;
}
}
Test
public static void main(String[] args) {
System.out.println(convert("seven billion one"
+ " hundred million thirty one thousand"
+ " three hundred thirty seven"));
}
Output
7100031337