Reputation: 41
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
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
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:
double
to get the number, stick with integer as the question clearly states it that reads an integer
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