I actually have two questions.
first how do I convert text (ex. One) to actual numbers (1) and plus to +. As I am trying to take the speech which starts with calculate and do the maths within that speech.
But for some reason speech recognition write down numbers and signs in text ( one plus three ) rather than (1+3).
The other question, is their any API or libraries that carry out heavy math equation like sin,cos integration and all the a level math. and giving out the process that it carried out to reach the solution.
What you're asking is not particularly difficult, but gets trickier as you increase the complexity. Depending on how much you need to understand, this may become very complicated. However for simple number plus number or number minus number, it's reasonably easy. To get you started, the following code will be able to deal with these two scenarios. Feel free to expand it as you wish. Also note that it has minimal error checking - in a production system you'll need quite a bit more of it.
import java.util.Map;
import java.util.HashMap;
public class Nums {
private static Map<String, Integer> nums = new HashMap<String, Integer>();
public static void main(String[] args) {
nums.put("zero", 0);
nums.put("one", 1);
nums.put("two", 2);
nums.put("three", 3);
nums.put("four", 4);
nums.put("five", 5);
nums.put("six", 6);
nums.put("seven", 7);
nums.put("eight", 8);
nums.put("nine", 9);
nums.put("ten", 10);
nums.put("eleven", 11);
nums.put("twelve", 12);
nums.put("thirteen", 13);
nums.put("fourteen", 14);
nums.put("fifteen", 15);
nums.put("sixteen", 16);
nums.put("seventeen", 17);
nums.put("eighteen", 18);
nums.put("nineteen", 19);
nums.put("twenty", 20);
nums.put("thirty", 30);
nums.put("forty", 40);
nums.put("fifty", 50);
nums.put("sixty", 60);
nums.put("seventy", 70);
nums.put("eighty", 80);
nums.put("ninety", 90);
String input = args[0].toLowerCase();
int pos;
String num1, num2;
int res1, res2;
if((pos = input.indexOf(" plus ")) != -1) {
num1 = input.substring(0, pos);
num2 = input.substring(pos + 6);
res1 = getNumber(num1);
res2 = getNumber(num2);
System.out.println(args[0] + " => " + res1 + " + " + res2 + " = " + (res1 + res2));
}
else if((pos = input.indexOf(" minus ")) != -1) {
num1 = input.substring(0, pos);
num2 = input.substring(pos + 7);
res1 = getNumber(num1);
res2 = getNumber(num2);
System.out.println(args[0] + " => " + res1 + " - " + res2 + " = " + (res1 - res2));
}
else {
System.out.println(args[0] + " => " + getNumber(args[0]));
}
}
private static int getNumber(String input) {
String[] parts = input.split(" +");
int number = 0;
int mult = 1;
String fact;
for(int i=parts.length-1; i>=0; i--) {
parts[i] = parts[i].toLowerCase();
if(parts[i].equals("hundreds") || parts[i].equals("hundred")) {
mult *= 100;
}
else if(parts[i].equals("thousands") || parts[i].equals("thousand")) {
if(number >= 1000) {
throw new NumberFormatException("Invalid input (part " + (i + 1) + ")");
}
mult = 1000;
}
else if(parts[i].equals("millions") || parts[i].equals("million")) {
if(number >= 1000000) {
throw new NumberFormatException("Invalid input (part " + (i + 1) + ")");
}
mult = 1000000;
}
else if(!nums.containsKey(parts[i])) {
throw new NumberFormatException("Invalid input (part " + (i + 1) + ")");
}
else {
number += mult * nums.get(parts[i]);
}
}
if(!nums.containsKey(parts[0])) {
number += mult;
}
return number;
}
}
This code handles numbers from 0 to 999,999,999 and doesn't handle negative numbers. Again, it shouldn't be too difficult to extend it to increase the range or handle negative numbers. Note that if you extend it to handle billions, you may need to switch from integer to long variables to hold the results.
Here are some test runs:
$ java Nums "three hundred nineteen million five hundred twenty three thousand six hundred eighteen"
three hundred nineteen million five hundred twenty three thousand six hundred eighteen => 319523618
$ java Nums "five hundred minus three hundred ninety nine"
five hundred minus three hundred ninety nine => 500 - 399 = 101
$ java Nums "thirty three plus seventeen"
thirty three plus seventeen => 33 + 17 = 50
$ java Nums zero
zero => 0
$ java Nums "one plus three"
one plus three => 1 + 3 = 4
$ java Nums "hundred thousand"
hundred thousand => 100000
$ java Nums "hundred thousand minus ten thousand"
hundred thousand minus ten thousand => 100000 - 10000 = 90000
Related
I made a program for the question and it's working fine, but in some cases it's not working like when I enter 656, it's showing like this:
The error
The code is showed below:
public static void main(String[] args) {
Scanner rx = new Scanner(System.in);
int ui,uiy,troll3,troll1;
float uix,uis,uiz,uit;
System.out.println("Enter a valid three digit number to calculate the frequency of the digits in it. \n");
ui = rx.nextInt();
if(ui>99&&ui<=999) {
uis = (float) ui;
//System.out.println(uis+" uis");
uix = uis / 10;
//System.out.println(uix+" uix");
uiy = (int) uix;
//System.out.println(uiy+" uiy");
troll3 = (int) ((uix - uiy) * 10); //1st digit
//System.out.println("3d " + troll3);
uiz = uix / 10;
//System.out.println(uiz+ " uiz");
troll1 = (int) uiz;
//System.out.println("1d " + troll1);
uit = (uiz - troll1) * 10;
//System.out.println(uit+" uit");
int troll2 = (int) uit;
//System.out.println("2d " + troll2);
if (troll1 == troll2 && troll1 == troll3) {
System.out.println("The number " + troll1 + " appears three times.");
} else if (troll1 != troll2 && troll2 != troll3 && troll1 != troll3) {
System.out.println("The number " + troll1 + " appears one time.");
System.out.println("The number " + troll2 + " appears one time.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll2) {
System.out.println("The number " + troll1 + " appears two times.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll3) {
System.out.println("The number " + troll3 + " appears two times.");
System.out.println("The number " + troll2 + " appears one time.");
} else if (troll2 == troll3) {
System.out.println("The number " + troll2 + " appears two times.");
System.out.println("The number " + troll1 + " appears one time.");
}
}
else{
System.out.println("The entered number is invalid");
}
}
It mostly gives an error when it consists of digit 5 in the middle. It shows an increment in values and swap in values. Please do help.
Thanks in advance! :-)
Why are you converting to float? float and double attempts to represent an infinite infinity of numbers (there are an infinite amount of integers. Between 2 integers, there are an infinite amount of numbers too: An infinite amount of infinities)... using only 32 bits. This is obviously impossible so instead only a few numbers are representable, and anything else is silently rounded to one of the select few. This means float and double introduce rounding errors.
After any math done to any double or float, == is broken. You can't use those; at best, you can try 'delta equality' (not a == b, but Math.abs(a - b) < 0.00001) but making the claim that your code works for all possible inputs becomes very difficult indeed, it's not going to be very fast, and the code readability isn't great either. So, don't.
Stop using floats, problem solved.
Your 'math' to get the individual digits is a bit circumspect and isn't going to just work if you replace things with int either. What you're missing is the % operator: Module (a.k.a. remainder).
Given, say, 656:
int in = 657;
int digit1 = in % 10;
in = in / 10;
System.out.println(in); // 65
System.out.println(digit1); // 7
int digit2 = in % 10;
in = in / 10;
System.out.println(in); // 6
System.out.println(digit1); // 5
int digit3 = in;
This question already has answers here:
How to count each digit in a range of integers?
(11 answers)
Closed last year.
I've been trying to find the most optimized way to compute the number of occurrences of each digit from 0 to 9 in a random range of numbers typed in by the user for a random personal project.
Say, the user enters 1 as the lower bound (inclusive) and 20 as the upper bound (inclusive). Output should be like this:
2 12 3 2 2 2 2 2 2 2
User can only enter positive integers.
Now, the below code runs fine for small range of numbers/ small bounds, however, as expected it takes 4 seconds+ on my laptop for large numbers/range.
I've been trying to find a way to make things quicker, I used modulus to get the digits thinking maybe string conversion is to blame, but it didn't increase speed that much. I want to reduce runtime to less than 2 seconds. There must be a way, but what? Here is my original code:
import java.util.Scanner;
public class CountDigitsRandomRange {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String g = s.nextLine();
while (!g.equals("0 0")) {
String[] n = g.split(" ");
long x = Long.parseLong(n[0]);
long y = Long.parseLong(n[1]);
long zero = 0;
long one = 0;
long two = 0;
long three = 0;
long four = 0;
long five = 0;
long six = 0;
long seven = 0;
long eight = 0;
long nine = 0;
for (long i = x; i <= y; i++) {
String temp = String.valueOf(i);
for (int j = 0; j < temp.length(); j++) {
if (temp.charAt(j) == '0') {
zero++;
}
if (temp.charAt(j) == '1') {
one++;
}
if (temp.charAt(j) == '2') {
two++;
}
if (temp.charAt(j) == '3') {
three++;
}
if (temp.charAt(j) == '4') {
four++;
}
if (temp.charAt(j) == '5') {
five++;
}
if (temp.charAt(j) == '6') {
six++;
}
if (temp.charAt(j) == '7') {
seven++;
}
if (temp.charAt(j) == '8') {
eight++;
}
if (temp.charAt(j) == '9') {
nine++;
}
}
}
System.out.println(zero + " " + one + " " + two + " "+three + " " + four
+ " " + five + " " + six + " " + seven + " " + eight + " " + nine);
g=s.nextLine();
}
}
}
I've seen some solutions online similar to my issue but they're mostly in C/C++, I don't get the syntax.
Here is a simple implementation that uses modulus. If you want a faster code, you will need to find some smart formula that gives you the result without performing the actual computation.
import java.util.Arrays;
public class Counter
{
private static long[] counts = new long[10];
public static void count(long x, long y)
{
Arrays.fill(counts, 0);
for(long val=x; val<=y; val++)
count(val);
}
public static void count(long val)
{
while(val>0)
{
int digit = (int)(val % 10);
counts[digit]++;
val /= 10;
}
}
public static void main(String[] args)
{
count(1, 20);
System.out.println(Arrays.toString(counts));
}
}
Output:
[2, 12, 3, 2, 2, 2, 2, 2, 2, 2]
So here is an issue you might not be aware of #Sammie. In my opinion, you should NOT use the seconds provided by your runner in Java to count time when it comes to making operations more efficient. As far as I am informed, a more objective calculation is to use internal methods of Java which depend on the CPU clock to count time. This way there is less variation between different PC's (although this I don't believe is fully eliminated). Please check my references below:
Clock milis (only use this if you cannot use the solution below)
Nanoseconds
Edit: Here is another stack overflow post discussing this matter. Nanoseconds seem to be preferable.
All you need to do after that is convert into minutes, and you should now be calculating more precisely.
I am practicing Java and I was trying to create a program to calculate the amount of ways an number could be divided using a set number of dividers.
For instance:
100 is the number and the dividers are 50,20,5. What are the possible divisions.
The answer would be:
Amount of 50 : 0, Amount of 20 : 0, Amount of 10 : 10
Amount of 50 : 0, Amount of 20 : 1, Amount of 10 : 8
Amount of 50 : 0, Amount of 20 : 2, Amount of 10 : 6
Amount of 50 : 0, Amount of 20 : 3, Amount of 10 : 4
Amount of 50 : 0, Amount of 20 : 4, Amount of 10 : 2
Amount of 50 : 1, Amount of 20 : 0, Amount of 10 : 5
Amount of 50 : 1, Amount of 20 : 1, Amount of 10 : 3
Amount of 50 : 1, Amount of 20 : 2, Amount of 10 : 1
Amount of 50 : 2
I wrote a code that asks the user an amount and 3 dividers. Now I am trying to figure out if there is a way to dynamically create a code for as many dividers as the user wants. The code is in a way very repetitive and there is a certain pattern to add another divider but I cannot figure out how to implement this dynamic change to the code.
The first code I came up with to do this is the following:
public class Test2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Insert the amount:");
int amount = scanner.nextInt();
List<Integer> dividers = new ArrayList<>();
System.out.println("Insert the first divider:");
int tempDivider = scanner.nextInt();
if (!dividers.contains(tempDivider)) {
dividers.add(tempDivider);
}
while (dividers.size()<3) {
System.out.println("Insert the next divider: (" + (3-dividers.size()) + " more to go)");
tempDivider = scanner.nextInt();
if (!dividers.contains(tempDivider)) {
dividers.add(tempDivider);
}
}
dividers.sort(Collections.reverseOrder());
System.out.print("Dividers are: ");
System.out.println(dividers);
int getal1 = dividers.get(0);
int getal2 = dividers.get(1);
int getal3 = dividers.get(2);
int fiftyAmount = amount / getal1;
int fiftyRemainder = amount % getal1;
for (int i = 0; i <= fiftyAmount; i++) {
int currentFiftyAmount = amount - (getal1 * i);
int twentyAmount = currentFiftyAmount / getal2;
int twentyRemainder = currentFiftyAmount % getal2;
if (twentyAmount == 0) {
StringBuilder output = new StringBuilder();
output.append("Amount of " + getal1 + " banknotes: " + i);
if (fiftyRemainder != 0) output.append(", Remainder: " + fiftyRemainder);
System.out.println(output);
} else {
for (int j = 0; j <= twentyAmount; j++) {
int currentTwentyAmount = currentFiftyAmount - (getal2 * j);
int tenAmount = currentTwentyAmount / getal3;
int tenRemainder = currentTwentyAmount % getal3;
if (tenAmount == 0) {
StringBuilder output = new StringBuilder();
output.append("Amount of " + getal1 + " banknotes: " + i + ", Amount of " + getal2 + " banknotes: " + j);
if (tenRemainder != 0) output.append(", Remainder: " + twentyRemainder);
} else {
StringBuilder output = new StringBuilder();
output.append("Amount of " + getal1 + " banknotes: " + i + ", Amount of " + getal2 + " banknotes: " + j +
", Amount of " + getal3 + " banknotes: " + tenAmount);
if (tenRemainder != 0) output.append(", Remainder: " + tenRemainder);
System.out.println(output);
}
}
}
}
}
}
I tried to make this more abstract to figure out a way to automate the creation of the extra dividing loops but I cannot figure it out.
The more abstract version I wrote is the following:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Insert the amount:");
int amount = scanner.nextInt();
List<Integer> dividers = new ArrayList<>();
System.out.println("Insert the first divider:");
dividers.add(scanner.nextInt());
int divider;
while (dividers.size()<2) {
System.out.println("Insert the next divider: (" + (2-dividers.size()) + " more to go)");
divider = scanner.nextInt();
if (!dividers.contains(divider)) {
dividers.add(divider);
}
}
dividers.sort(Collections.reverseOrder());
System.out.print("Dividers are: ");
System.out.println(dividers);
int divided1Amount = amount / dividers.get(0);
int divided1Remainder = amount % dividers.get(0);
for (int i = 0; i <= divided1Amount; i++) {
int currentDivided1Amount = amount - (dividers.get(0) * i);
int divided2Amount = currentDivided1Amount / dividers.get(1);
int divided2Remainder = currentDivided1Amount % dividers.get(1);
if (divided2Amount == 0) {
StringBuilder output = new StringBuilder();
output.append(dividers.get(0) + ":" + i);
if (divided1Remainder != 0) {
output.append(", Remainder: " + divided1Remainder);
}
System.out.println(output);
} else {
StringBuilder output = new StringBuilder();
output.append(dividers.get(0) + ":" + i + "," + dividers.get(1) + ":" + divided2Amount);
if (divided2Remainder != 0) {
output.append(", Remainder: " + divided2Remainder);
}
System.out.println(output);
}
}
}
}
This is also available on GitHub: https://github.com/realm1930/rekendin/blob/master/src/Main.java
Could anybody please enlighten me. I am sorry if I am not clear at my description of the issue.
Thanks
While a fixed number of dividers can be well approached with nested loops, I suggest for the general case to write the solution as a recursive function.
This problem is a good fit for dynamic programming. What I mean by this is that the problem can be broken down into simpler subproblems, and in this way the solution is naturally implemented with recursion. For instance, in your example of expressing 100 as a sum of multiples of 50, 20, and 10, there are three solutions found that all use one 50:
Amount of 50 : 1, Amount of 20 : 0, Amount of 10 : 5
Amount of 50 : 1, Amount of 20 : 1, Amount of 10 : 3
Amount of 50 : 1, Amount of 20 : 2, Amount of 10 : 1
Look at this as solving the subproblem of finding the ways that value 50 can be expressed as multiples of 20 and 10 (that is, 50 is equal to 20*0 + 10*5, 20*1 + 10*3 and 20*2 + 10*1). So you can divide-and-conquer the original problem in this sense.
Let X be the number (e.g. 100) to express, and D1, D2, ... DN the dividers. Here is a possible outline:
If there is just one divider, N = 1, it is easy: there just zero or one solution depending on whether D1 divides X.
Otherwise, possible solutions might have D1 with any multiple from 0, 1, ..., X/D1. So make a loop m1 = 0, 1, ..., X/D1, and recursively solve the subproblem having X' = X - m1*D1 and the remaining dividers D2, ..., DN. This subproblem has one fewer divider, so after enough recursions it reduces to the N = 1 case.
That solves the problem. Note, though, that fully recursing may result in a combinatorially vast number of subproblems to solve. So for efficient solution it is a good idea to store or "memoize" the solutions of previously-solved subproblems in a table so that work isn't repeated.
Other thoughts:
Let Q be the greatest common divisor (GCD) of all the dividers {D1, ..., DN}. If X isn't divisible by Q, then there are no solutions, in which case we can skip the above recursive search entirely. E.g. there is no way to express X = 103 with dividers 50, 20, and 10. This GCD test can also be applied to every subproblem so that some recursive calls can return early.
This problem is a kind of Diophantine equation, more specifically, it is related to the Frobenius coin problem and Frobenius numbers. There is a mathoverflow post discussing it.
I need to print the factors of a perfect number. Here's the gist of my main class:
ArrayList<Integer> perfNums = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the upperbound: ");
upperbound = in.nextInt();
for (int i = 1; i <= upperbound; i++) {
if (isPerfect(i)) { //boolean to check if number is a perfect number
perfNums.add(i);
}
}
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for (int i = 0; i < perfNums.size(); i++) {
System.out.print(perfNums.get(i) + " = ");
printFactor((int)perfNums.get(i));
System.out.println();
}
Here's the printFactor class.
private static void printFactor(int number){
int factor = 1;
while(factor < number){
if (number%factor == 0) System.out.print(factor+ " + ");
//I don't know how to print the + sign otherwise.
factor++;
}
}
And here's a sample output:
Enter the upperbound: 10000
Perfect numbers between 1 and 10000 are:
6 = 1 + 2 + 3 +
28 = 1 + 2 + 4 + 7 + 14 +
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 +
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 +
I've got the main gist of it but I've struggled with an output issue. Due to the restrictions of my online submission system, my output needs to fit exact specifications.
My question is how do I go about printing all the factors of my perfect number but removing the + sign at the end? (e.g)6 = 1 + 2 + 3
I'm not too sure of many methods to print from a while loop. Would a for-loop be better for my goals? Or are there alternative methods to print the factors of a number?
The least amount of change to address this might be something like this:
private static void printFactor(int number)
System.out.print(1);
int factor = 2;
while (factor<number) {
if (number%factor == 0) System.out.print(" + " + factor);
factor++;
}
}
1 is always a factor, so you can print that before the loop and then prepend + to every subsequent factor.
You should cache the output you want to print into a StringBuilder. Then you are able to remove the last plus sign before you print the whole String. It also has a better performance.
private static void printFactor(int number)
{
StringBuilder output = new StringBuilder();
int factor = 1;
while (factor < number)
{
if (number % factor == 0)
output.append(factor + " + ");
factor++;
}
// remove last plus sign
output.deleteCharAt(output.length() - 1);
// print the whole string
System.out.print(output.toString());
}
Since factor starts from value 1 and number % 1 == 0 will always be true, you might print 1 first and then flip factor and + in System.out.print. Like this:
private static void printFactor(int number) {
if(number > 0) {
System.out.print(1);
}
int factor = 2;
while (factor<number) {
if (number % factor == 0) {
System.out.print(" + " + factor);
}
factor++;
}
}
Not the best solution, but it will do the job.
Try to create a variable String numb and use substring method like this:
String numb ="";
while(factor<number){
if(number%factor == 0)
numb= numb + factor+ " + ";
factor++;
}
System.out.print(numb.substring(0, numb.trim().length()-1));
Just for the sake of using Java 8 :)
private static void printFactor(int number){
System.out.println(IntStream.range(1, number)
.filter(p -> number % p == 0)
.mapToObj(i -> String.valueOf(i))
.collect(Collectors.joining(" + ")));
}
Thanks everyone for the quick response. You all have been a lifesaver, and I managed to pick up some new things to consider when I code in the future.
Anyway, while waiting for a reply I was fiddling with the code and came up with a rather inelegant solution, if anybody's interested. Here's the changes to the main class:
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for(int i=0; i<perfNums.size(); i++){
System.out.print(perfNums.get(i) + " = ");
outputString = printFactor2(perfNums.get(i));
if(outStr.endsWith(" + ")) outStr = outStr.substring(0, outStr.length()-3);
//because the submission system would cry foul with even a single extra space
System.out.println(outStr);
}
And here's the changes to the printFactor class:
private static String printFactor2(int number){
String out = "";
int factor = 1;
while(factor<number){
if(number%factor == 0) out += factor + " + ";
factor++;
}
return out;
}
Basically, what I did was append the factors to a string, then removing the trailing + sign using the substring method. On hindsight, I probably should've called the substring method inside the printFactor class instead. Something like return out.substring(0, out.length()-3); perhaps?
Nevertheless, thanks everyone!
I am doing a beginner Java course and working on methods. My assignment is to print inputted numbers between 1-999 as words. All of them work except for any "teen" number in the hundreds (110, 114, 212, 919, etc.) The regular teens work fine, but my method for any 3digit numbers to identify -teens (as they would have a second digit of 1) doesn't.
I ran your program and it seemed to be working fine for the -teens in the 3 digits (e.g. 110,114,etc.)
However, it was not working for the two digit -teens like 14, 17, etc.
Your code
if((numInput>=10)&&(numInput<=19)){//will initiate the teens subroutine
teens(numInput);}
Should be changed to
if((numInput>=10)&&(numInput<=19)){//will initiate the teens subroutine
teens(onesDigit);}
The teens() subroutine takes the ones digit as a parameter, and not the whole number.
Also, there is no need for the hundredsTeens variable. You could just pass the onesDigit instead.
I think you forgot something in your code.
You have identifying two cases : the ten digit is 1 or not. There are three cases.
1- <1
2- ==1
3- >1
Then you use double tensDigit = (numInput % 100) / 10; but this it not a digit! 114 returns 1.4, you should declare a digit as an integer.
Try this first (with digit as double...) :
if (tensDigit < 1){
ones(onesDigit); // only display the last digit
}
else if(1==Integer.parseInt(Double.toString(tensDigit).substring(0, 1))){
teens(hundredsTeens);
}
else if (tensDigit > 1){
tens(tensDigit);
System.out.print(" ");
ones(onesDigit);
}
}
You will see your mistake, and then try to put real digit to symplify your code readability.
Here is the answer to print numbers from 0 to 99999 in words using some Java 8. Run the program passing the number as command line argument.
public static final Map<Integer, String> DICTIONARY = Collections.unmodifiableMap(Stream
.of(new SimpleEntry<>(0, "zero"), new SimpleEntry<>(1, "one"), new SimpleEntry<>(2, "two"),
new SimpleEntry<>(3, "three"), new SimpleEntry<>(4, "four"), new SimpleEntry<>(5, "five"),
new SimpleEntry<>(6, "six"), new SimpleEntry<>(7, "seven"), new SimpleEntry<>(8, "eight"),
new SimpleEntry<>(9, "nine"), new SimpleEntry<>(10, "ten"), new SimpleEntry<>(11, "eleven"),
new SimpleEntry<>(12, "tweleve"), new SimpleEntry<>(13, "thirteen"), new SimpleEntry<>(14, "fourteen"),
new SimpleEntry<>(15, "fifteen"), new SimpleEntry<>(16, "sixteen"), new SimpleEntry<>(17, "seventeen"),
new SimpleEntry<>(18, "eighteen"), new SimpleEntry<>(19, "nineteen"), new SimpleEntry<>(20, "twenty"),
new SimpleEntry<>(30, "thirty"), new SimpleEntry<>(40, "forty"), new SimpleEntry<>(50, "fifty"),
new SimpleEntry<>(60, "sixty"), new SimpleEntry<>(70, "seventy"), new SimpleEntry<>(80, "eighty"),
new SimpleEntry<>(90, "ninety"), new SimpleEntry<>(100, "hundred"), new SimpleEntry<>(1000, "thousand"))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
public static void main(String args[]) {
try {
if (args.length == 0 || args.length > 1) {
throw new RuntimeException(
"Please run the program with only one number in the range of 0 to 99999");
}
Integer givenNumber = Integer.parseInt(args[0]);
NumbersEnglishDictionary.DICTIONARY.entrySet()
.stream()
.filter(e -> e.getKey().equals(givenNumber))
.findAny()
.ifPresent(System.out::print);
if (givenNumber < 100) {
System.out.print(givenNumber + " = " + NumbersEnglishDictionary.DICTIONARY.get((givenNumber / 10) * 10)
+ " " + NumbersEnglishDictionary.DICTIONARY.get(givenNumber % 10));
return;
}
if (givenNumber > 100 && givenNumber < 1000) {
System.out.print(givenNumber + " = " + NumbersEnglishDictionary.DICTIONARY.get(givenNumber / 100)
+ " hundred " + NumbersEnglishDictionary.DICTIONARY.get(((givenNumber / 10) % 10) * 10) + " "
+ NumbersEnglishDictionary.DICTIONARY.get(givenNumber % 10));
return;
}
if (givenNumber > 1000 && givenNumber < 10000) {
System.out.print(givenNumber + " = " + NumbersEnglishDictionary.DICTIONARY.get(givenNumber / 1000)
+ " thousand " + NumbersEnglishDictionary.DICTIONARY.get((givenNumber / 100) % 10) + " hundred "
+ NumbersEnglishDictionary.DICTIONARY.get(((givenNumber / 10) % 10) * 10) + " "
+ NumbersEnglishDictionary.DICTIONARY.get(givenNumber % 10));
return;
}
if (givenNumber > 10000 && givenNumber < 100000) {
System.out.print(
givenNumber + " = " + NumbersEnglishDictionary.DICTIONARY.get(((givenNumber / 1000) / 10) * 10)
+ " " + NumbersEnglishDictionary.DICTIONARY.get((givenNumber / 1000) % 10)
+ " thousand " + NumbersEnglishDictionary.DICTIONARY.get((givenNumber / 100) % 10)
+ " hundred " + NumbersEnglishDictionary.DICTIONARY.get(((givenNumber / 10) % 10) * 10)
+ " " + NumbersEnglishDictionary.DICTIONARY.get(givenNumber % 10));
return;
}
} catch (NumberFormatException e) {
throw new RuntimeException("Please run the program with only one number in the range of 0 to 99999");
}
}