Search code examples
javaarraysfor-loopnumberswords

Convert numbers into word-numbers (using loop and arrays)


How do I write a simple program that converts numbers into word-numbers, using loops and arrays?

like this: input: 1532 output: One Five Three Two

Here's what I tried:

class tallTilOrd 
{ 
    public static void main (String [] args) 
    { 
        Scanner input = new Scanner (System.in); 
        String [] tall = {"null", "en" , "to", "tre", "fire" , 
                          "fem", "seks", "syv", "åtte", "ni", "ti"); 
        System.out.println("Tast inn et ønsket tall"); 
        int nummer = input.nextInt(); 

        for (int i = 0; i<tall.length; i++) 
        { 
           if(nummer == i) 
           { 
              System.out.println(tall[i]); 
           } 
         } 
     } 
}

Solution

  • Scanner input = new Scanner (System.in);

        String in = Integer.toString(input.nextInt());
        String [] tall = {"null", "en" , "to", "tre", "fire" , "fem", "seks", "syv", "åtte", "ni", "ti"};       
    
        for(char c : in.toCharArray()){
            int i = (int) (c-'0');
            for (int j = 0; j<tall.length; j++) {
                if(i == j){
                    System.out.print (tall[j] + " ");
                }
            }
        }