문제

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]); 
           } 
         } 
     } 
}
도움이 되었습니까?

해결책

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] + " ");
            }
        }
    }

다른 팁

I give you a hint:

You could convert your Integer input into a String and then process each Character of that string. Check out the javadoc for String to figure out how to do it ;-)

Now I'm not sure this is the perfect way to do it, but it would be a possible one.

Instead of iterating over the length of your tall array, you need to iterate over the digits of nummer (to do this, check out the methods String.valueOf(int), String.charAt(int) and String.length()). Then use those digits as indices for tall to get their string representation.

A few notes:

In the code you provided, you need to use == instead of =. == is for comparison, = is for assignment.

Instead of looping through the predefined array, loop through the input. Instead of treating the number entered as an int, treat it as a string and then convert each character in the string into a number, which you can use as an index to fetch the corresponding string from your array.

Also, note that println prints a newline each time.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top