Need to print this number format as mentioned below in text format example: 1234567890 output: onetwothree....so on!
is it possible to do this?
Need to print this number format as mentioned below in text format example: 1234567890 output: onetwothree....so on!
is it possible to do this?
You could try using Hashmap: https://www.w3schools.com/java/java_hashmap.asp
For each digit, make a key-value pair, integer to string, then use a loop to iterate through your string with numbers, comparing the number to the HashMap, and append value matching provided key to result string
public static void main(String[] args) {
HashMap<Integer, String> numberWords = new HashMap<Integer, String>();
numberWords.put(1, "One");
numberWords.put(2, "Two");
numberWords.put(3, "Three");
numberWords.put(4, "Four");
numberWords.put(5, "Five");
numberWords.put(6, "Six");
numberWords.put(7, "Seven");
numberWords.put(8, "Eight");
numberWords.put(9, "Nine");
numberWords.put(0, "Zero");
String numbers = "1234523";
String result = "";
for(int i =0; i< numbers.length(); i++) {
char current = numbers.charAt(i);
result = result + " " + numberWords.get(Character.getNumericValue(current));
}
System.out.println(result);
}
Although, as the first comment says, this does look like homework problem, and hashMap may be a bit of an overkill
There's nothing, in Java SE Specification, that can convert number to its respective word.
One way to achieve what you want, is to use java.util.HashMap<K, V>
, but better would be to use array, as:
String[] numWords = new String[] {"zero", "one", ... "hundred"};
public String convertNumberToWord(int n) {
return numWords[n];
}
However, this doesn't make much sense to implement such a method. You'll need to create or load dynamically all the string words, which you can't do, and even is not reasonable thing to do, imho.
To be honest, I can't even think of anything, at all, in computer science world, that can provide such a functionality, because, numbers are stored as binary values, and characters are also number codes (from the Unicode). Computers do not understand texts.
To my knowledge, there's no library that does this, but it's a simple enough method to convert a string of digits into words:
String convertStringToNumbers(String input) {
String result = "";
for(int i = 0; i < input.length(); i++) {
int currentDigit = Character.getNumericValue(input.charAt(i));
switch (currentDigit) {
case 0:
result += "zero";
break;
case 1:
result += "one";
break;
//add cases for the other digits
}
}
return result;
}