Orcho Siddiqui
Orcho Siddiqui

Reputation: 41

transform digits of a number into words

I've coded a program that takes a number and shows the digits of the number in words. So far, my code counts the numbers from the right. How can I fix this?

My code:

  /*/  Write a program that reads an integer and extracts and displays each digit 
       of the integer in English. So, if the user types in 451, 
       the program will display four five one   /*/

 import static java.lang.System.*;
 import java.util.*;

 class Practice_Problems04_JavaPrograms_Task09{
     public static void main(String[] args){
         Scanner orcho = new Scanner(in);
         String[] myArray = {"zero" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine"};
         out.print("Please type your number: ");
         double number = orcho.nextDouble();

         for(int count = 0; count <= number; count++){
             number /= 10.0;
             out.print(myArray[(int)(10 * (number - (int)number))] + " ");
         }
         out.println();

         orcho.close();
     }
 }

Upvotes: 0

Views: 193

Answers (2)

Gerald Schneider
Gerald Schneider

Reputation: 17797

Why bother with numbers at all? You want the characters, so you can use the string you get from the input:

Scanner orcho = new Scanner(System.in);
String[] myArray = {"zero" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine"};
System.out.print("Please type your number: ");
String number = orcho.next();
for (int i=0; i < number.length(); i++) {
    System.out.println(myArray[number.charAt(i)-48]);
    // -48 because 0 has the ASCII value 48
}

Upvotes: 1

Jorge Campos
Jorge Campos

Reputation: 23361

Since this is an exercise and it is for learning purposes, I will not provide any code. Just a set of steps of what you should do:

  1. You already have an array with numbers name, that is fine
  2. Don't use a double to get the number, stick with integer as the question clearly states it that reads an integer
  3. Convert it to a string
  4. Loop each character of the string
  5. Convert each character to an integer again (inside the loop)´
  6. Just print that position from your name numbers array. Hint: With a method that do not create a new line for each printing :)

That would be fine!
Go learning how to do each of these steps if you don't!

Another hint: If you are gona convert the input to string just get it as string first. But you will have to check if it is only numbers right? ;)

Upvotes: 1

Related Questions