Problem10.Number as words

Здравейте,дали някой би искал да сподели случайно как сте успели да решите тази задача без да използвате цикъл,който все още не сме разглеждали?Аз не успях да се сетя за адекватен начин .

Здравей,
аз изчетох интернета и не успях също да намеря начин за решаване, който да влиза във взетия досега материал… И за мен е интересно дали все пак има начин да се реши без arrays и ако не, защо такъв тип задача е включена в домашното… :smiley:

Това е моето решение, като достигнах до него след разглеждане на доста подобни, но ползващи цикли, в нета. Цикъл не ползвам, но arrays, да. Проверявам с различни инпути, работи, но не съм сигурна, че всичко в кода е правилно :slight_smile:

1 Like

Това е моето решение, и мен ме измъчи

Scanner scanner = new Scanner(System.in);

    System.out.println("Enter a number between 0 and 999: ");
    int number = Integer.parseInt(scanner.nextLine());

    int hundreds = number / 100;
    int tensAndOnes;

    if (number > 99){
        tensAndOnes = number % 100;
    } else {
        tensAndOnes = number * 1;
    }

    int ones = number % 10;

    switch (hundreds)
    {
        case 1: System.out.println("One hundred "); break;
        case 2: System.out.println("Two hundred "); break;
        case 3: System.out.println("Three hundred "); break;
        case 4: System.out.println("Four hundred "); break;
        case 5: System.out.println("Five hundred "); break;
        case 6: System.out.println("Six hundred "); break;
        case 7: System.out.println("Seven hundred "); break;
        case 8: System.out.println("Eight hundred "); break;
        case 9: System.out.println("Nine hundred "); break;
    }

    if (hundreds >= 1 && tensAndOnes >= 1) System.out.println("and ");

    if (tensAndOnes >= 20 && tensAndOnes < 30) System.out.println("Twenty");
    else if (tensAndOnes >= 30 && tensAndOnes < 40) System.out.println("Thirty");
    else if (tensAndOnes >= 40 && tensAndOnes < 50) System.out.println("Fourty");
    else if (tensAndOnes >= 50 && tensAndOnes < 60) System.out.println("Fifty");
    else if (tensAndOnes >= 60 && tensAndOnes < 70) System.out.println("Sixty");
    else if (tensAndOnes >= 70 && tensAndOnes < 80) System.out.println("Seventy");
    else if (tensAndOnes >= 80 && tensAndOnes < 90) System.out.println("Eighty");
    else if (tensAndOnes >= 90 && tensAndOnes < 100) System.out.println("Ninety");

    switch(tensAndOnes)
    {
        case 1: System.out.println("One"); break;
        case 2:System.out.println("Two"); break;
        case 3: System.out.println("Three"); break;
        case 4: System.out.println("Four"); break;
        case 5: System.out.println("Five"); break;
        case 6: System.out.println("Six"); break;
        case 7: System.out.println("Seven"); break;
        case 8: System.out.println("Eight"); break;
        case 9: System.out.println("Nine"); break;
        case 10: System.out.println("Ten"); break;
        case 11: System.out.println("Eleven"); break;
        case 12: System.out.println("Twelve"); break;
        case 13: System.out.println("Thirteen"); break;
        case 14: System.out.println("Fourteen"); break;
        case 15: System.out.println("Fifteen"); break;
        case 16: System.out.println("Sixteen"); break;
        case 17: System.out.println("Seventeen"); break;
        case 18: System.out.println("Eighteen"); break;
        case 19: System.out.println("Nineteen"); break;
    }
    if (tensAndOnes > 20)
    {
        switch (ones)
        {
            case 1: System.out.println("-one"); break;
            case 2: System.out.println("-two"); break;
            case 3: System.out.println("-three"); break;
            case 4: System.out.println("-four"); break;
            case 5: System.out.println("-five"); break;
            case 6: System.out.println("-six"); break;
            case 7: System.out.println("-seven"); break;
            case 8: System.out.println("-eight"); break;
            case 9: System.out.println("-nine"); break;
        }
    }
    if (number == 0) System.out.println("Zero");
    System.out.println();
}
    }
7 Likes

Здравей:) Аз също не разбирам защо слагат задачи ,които реално няма как да решим оптмално към момента .

1 Like

Да ,това и аз го разглеждах,но не успях да го докарам да работи правилно.Благодаря иначе сега ще разгледам твоето решение:)

За точно това решение не съм се сетила,а реално е само със знанията които имаме до момента .Просто е доста писане ,но е доста добра идея.Благодаря за отговора беше ми доста от полза:)

Здравейте на всички! И аз доста се чудих за тази задача. Предадох друго решение, после написах ново решение, което според мен е по-добро, но не успях да използвам в тази задача substring метода, защото ми даваше грешка, въпреки че дължината на substring-a не беше 0 - това ми трябваше за промяната на главните букви. накрая го направих с “.toLowerCase();” Ето и решението ми:
import java.util.Scanner;

public class NumberasWords2 {
public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    int number = Integer.parseInt(sc.nextLine());

    int hundreds = number / 100;
    int tensAndOnes = number % 100;
    int tens = (number / 10) % 10;
    int ones = number % 10;
    String hundredsAsWords = "";
    String tensAndOnesAsWords = "";
    String numAsWord0to9 = "";

    switch (hundreds) {
        case 1:
            hundredsAsWords = "One hundred";
            break;
        case 2:
            hundredsAsWords = "Two hundred";
            break;
        case 3:
            hundredsAsWords = "Three hundred";
            break;
        case 4:
            hundredsAsWords = "Four hundred";
            break;
        case 5:
            hundredsAsWords = "Five hundred";
            break;
        case 6:
            hundredsAsWords = "Six hundred";
            break;
        case 7:
            hundredsAsWords = "Seven hundred";
            break;
        case 8:
            hundredsAsWords = "Eight hundred";
            break;
        case 9:
            hundredsAsWords = "Nine hundred";
            break;
    }

    switch (tens) {
        case 1:
            if (ones == 0) {
                tensAndOnesAsWords = "Ten";
            } else if (ones == 1) {
                tensAndOnesAsWords = "Eleven";
            } else if (ones == 2) {
                tensAndOnesAsWords = "Twelve";
            } else if (ones == 3) {
                tensAndOnesAsWords = "Thirteen";
            } else if (ones == 4) {
                tensAndOnesAsWords = "Fourteen";
            } else if (ones == 5) {
                tensAndOnesAsWords = "Fifteen";
            } else if (ones == 6) {
                tensAndOnesAsWords = "Sixteen";
            } else if (ones == 7) {
                tensAndOnesAsWords = "Seventeen";
            } else if (ones == 8) {
                tensAndOnesAsWords = "Eighteen";
            } else if (ones == 9) {
                tensAndOnesAsWords = "Nineteen";
            }
            break;
        case 2:
            tensAndOnesAsWords = "Twenty";
            break;
        case 3:
            tensAndOnesAsWords = "Thirty";
            break;
        case 4:
            tensAndOnesAsWords = "Forty";
            break;
        case 5:
            tensAndOnesAsWords = "Fifty";
            break;
        case 6:
            tensAndOnesAsWords = "Sixty";
            break;
        case 7:
            tensAndOnesAsWords = "Seventy";
            break;
        case 8:
            tensAndOnesAsWords = "Eighty";
            break;
        case 9:
            tensAndOnesAsWords = "Ninety";
            break;
    }

    switch (ones) {
        case 1:
            numAsWord0to9 = "One";
            break;
        case 2:
            numAsWord0to9 = "Two";
            break;
        case 3:
            numAsWord0to9 = "Three";
            break;
        case 4:
            numAsWord0to9 = "Four";
            break;
        case 5:
            numAsWord0to9 = "Five";
            break;
        case 6:
            numAsWord0to9 = "Six";
            break;
        case 7:
            numAsWord0to9 = "Seven";
            break;
        case 8:
            numAsWord0to9 = "Eight";
            break;
        case 9:
            numAsWord0to9 = "Nine";
            break;
    }

 //   String substringTens1;
 //   substringTens1 = tensAndOnesAsWords.substring(0, 1);
 //   String substringTens2 = tensAndOnesAsWords.substring(1);

 //   String substringOnes1;
  //  substringOnes1 = numAsWord0to9.substring(0, 1);
 //   String substringOnes2 = numAsWord0to9.substring(1);


    if (number >= 100) {
        if (number % 100 == 0) {
            System.out.println(hundredsAsWords);
        } else if (tens < 1 && ones > 0) {
            System.out.println(hundredsAsWords + " and " + numAsWord0to9.toLowerCase());
        } else if (tens == 1 || (tens > 1 && ones == 0)) {
            System.out.println(hundredsAsWords + " and " + tensAndOnesAsWords.toLowerCase());
        } else if (tens > 1 && ones > 0) {
            System.out.println(hundredsAsWords +
                    " and " + tensAndOnesAsWords.toLowerCase() + " " + numAsWord0to9.toLowerCase());
        }

    } else if (number >= 10) {
        if (tens > 1 && ones > 0) {
            System.out.println(tensAndOnesAsWords + " " + numAsWord0to9.toLowerCase());
        } else if (tens == 1 || (tens > 1 && ones == 0)) {
            System.out.println(tensAndOnesAsWords);
        }
    } else {
        if (ones > 0) {
            System.out.println(numAsWord0to9);
        }else{
            System.out.println("Zero");
        }

    }
}

}

4 Likes

Hello forum!

This task gave me a lot of trouble. Finally I did it without using arrays and loops. I used substring method.

import java.util.Scanner;

public class NumberAsWords {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    int n1,n2;
    String output = "";
    String output1 = "";
    String output2 = "";

    if (n == 0 ) {
        output2 = "Zero";
    }
    if (n >= 100 && n <= 999) {
        n1 = n/100; //divide by 100 and int will truncate
        // it to smaller number. Example 123/100 =1.23 truncate to 1
        if(n % 100==0 ) { //if n is 100,200... to 900 print this...
            switch(n1){

                case 1: output = "One hundred "; break;
                case 2: output = "Two hundred "; break;
                case 3: output = "Three hundred "; break;
                case 4: output = "Four hundred "; break;
                case 5: output = "Five hundred "; break;
                case 6: output = "Six hundred "; break;
                case 7: output = "Seven hundred "; break;
                case 8: output = "Eight hundred "; break;
                case 9: output = "Nine hundred "; break;
            }
        }
        if(n % 100!=0) {
            switch(n1){

                case 1: output = "One hundred and "; break;
                case 2: output = "Two hundred and "; break;
                case 3: output = "Three hundred and "; break;
                case 4: output = "Four hundred and "; break;
                case 5: output = "Five hundred and "; break;
                case 6: output = "Six hundred and "; break;
                case 7: output = "Seven hundred and "; break;
                case 8: output = "Eight hundred and "; break;
                case 9: output = "Nine hundred and "; break;
            }
            n = n % 100;// it will remove first number from n.
            // Example: 123 will become 23
        }
    }
    if (n >= 20 && n <= 99) {
        n2 = n/10;//divide by 10 and integer will truncate
        // it to smaller number. Example: 25/10 = 2.5 and int
        // will truncate it to number 2
        switch(n2){

            case 2: output1 = "Twenty ";break;
            case 3: output1 = "Thirty ";break;
            case 4: output1 = "Forty ";break;
            case 5: output1 = "Fifty ";break;
            case 6: output1 = "Sixty ";break;
            case 7: output1 = "Seventy ";break;
            case 8: output1 = "Eighty ";break;
            case 9: output1 = "Ninety ";break;
        }
        n = n % 10; //it will remove first number from n.
        // Example: 23 will become 3
    }

    if (n >= 0 && n <= 19) {
        switch(n) {

            case 1: output2 = "One";break;
            case 2: output2 = "Two";break;
            case 3: output2 = "Three";break;
            case 4: output2 = "Four";break;
            case 5: output2 = "Five";break;
            case 6: output2 = "Six";break;
            case 7: output2 = "Seven";break;
            case 8: output2 = "Eight";break;
            case 9: output2 = "Nine";break;
            case 10: output2 = "Ten";break;
            case 11: output2 = "Eleven";break;
            case 12: output2 = "Twelve";break;
            case 13: output2 = "Thirteen";break;
            case 14: output2 = "Fourteen";break;
            case 15: output2 = "Fifteen";break;
            case 16: output2 = "Sixteen";break;
            case 17: output2 = "Seventeen";break;
            case 18: output2 = "Eighteen";break;
            case 19: output2 = "Nineteen";break;
        }
    }
    String finalPrint = output +""+output1+""+ output2;
    //join all strings in one

    String firstLetter = finalPrint.substring(0,1);
    String remainingLetters = finalPrint.substring(1, finalPrint.length());
    // with or without finalPrint.length() it works because substring
    // methode considers all other letters after 1 to the end of
    // string lowercase.

    // change the first letter to uppercase
    firstLetter = firstLetter.toUpperCase();
    // rest of the letter to lowercase
    remainingLetters = remainingLetters.toLowerCase();

    // join the two substrings
    finalPrint = firstLetter + remainingLetters;

    System.out.print(finalPrint);
}

}

5 Likes

Тук споделям линк с полезни методи за String Class :slightly_smiling_face:

4 Likes

Здравейте,

Малко си поиграх допълнително със задачата и я направих да работи със числа от 9999 до 0 и накрая освен да ги изписва с думи, да дава сумата на числата, от които са съставени

Според мен най-важното, което човек трябва да усвои е как да намира мястото на единиците, десетиците, стотиците и хилядните и как да отдели съответния digit, за да може да извържва различни операции с него. Всичко останало са някакви switch - ове, които лесно се разписват

//Read input from the client
Scanner scanner = new Scanner(System.in);
System.out.println(“Enter a number from 9999 to 0”);
int num = scanner.nextInt();

    //Finding the thousand place of the number
    int digits_at_thou_place=(num/1000)%10;
    //Finding the hundred place of the number
    int digits_at_hund_place=(num/100)%10;
    //Finding the tenth place of the number
    int digits_at_tens_place=(num/10)%10;
    //Finding the one place of the number
    int digit_at_one_place=num%10;

    //Provide the name of the num in thousands
    switch (digits_at_thou_place){
        case 1:
            System.out.print("One Thousand");
            break;
        case 2:
            System.out.print("Two Thousands");
            break;
        case 3:
            System.out.print("Three Thousands");
            break;
        case 4:
            System.out.print("Four Thousands");
            break;
        case 5:
            System.out.print("Five Thousands");
            break;
        case 6:
            System.out.print("Six Thousands");
            break;
        case 7:
            System.out.print("Seven Thousands");
            break;
        case 8:
            System.out.print("Eight Thousands");
            break;
        case 9:
            System.out.print("Nine Thousands");
            break;
    }



   //Provide the name of the num in hundreds
    switch(digits_at_hund_place){
       case 1:
           System.out.print(" One Hundred");
           break;
       case 2:
           System.out.print(" Two Hundred");
           break;
       case 3:
           System.out.print(" Three Hundred");
           break;
       case 4:
           System.out.print(" Four Hundred");
           break;
       case 5:
           System.out.print(" Five Hundred");
           break;
       case 6:
           System.out.print(" Six Hundred");
           break;
       case 7:
           System.out.print(" Seven Hundred");
           break;
       case 8:
           System.out.print(" Eight Hundred");
           break;
       case 9:
           System.out.print(" Nine Hundred");
           break;
   }

    if (digits_at_hund_place >=1 && digits_at_tens_place >= 1 ) {
        System.out.print(" and ");
    }

    if ((digits_at_tens_place == 1 )&& (digit_at_one_place >=1)){

        //Provide the name of the num in teens
        if (digits_at_tens_place == 1 && digit_at_one_place == 1) {
            System.out.print(" Eleven");
        }
        if (digits_at_tens_place == 1 && digit_at_one_place == 2) {
            System.out.print(" Twelve");
        }
        if (digits_at_tens_place == 1 && digit_at_one_place == 3) {
            System.out.print(" Thirteen");
        }
        if (digits_at_tens_place == 1 && digit_at_one_place == 4) {
            System.out.print(" Fourteen");
        }
        if (digits_at_tens_place == 1 && digit_at_one_place == 5) {
            System.out.print(" Fifteen");
        }
        if (digits_at_tens_place == 1 && digit_at_one_place == 6) {
            System.out.print(" Sixteen");
        }
        if (digits_at_tens_place == 1 && digit_at_one_place == 7) {
            System.out.print(" Seventeen");
        }
        if (digits_at_tens_place == 1 && digit_at_one_place == 8) {
            System.out.print(" Eighteen");
        }
        if (digits_at_tens_place == 1 && digit_at_one_place == 9) {
            System.out.print(" Nineteen");
        }
        } else {
        //Provide the name of the num in tens
        switch (digits_at_tens_place){
            case 1:
                System.out.print("Ten");
                break;
            case 2:
                System.out.print("Twenty");
                break;
            case 3:
                System.out.print("Thirty");
                break;
            case 4:
                System.out.print("Forty");
                break;
            case 5:
                System.out.print("Fifty");
                break;
            case 6:
                System.out.print("Sixty");
                break;
            case 7:
                System.out.print("Seventy");
                break;
            case 8:
                System.out.print("Eighty");
                break;
            case 9:
                System.out.print("Ninety");
                break;

        }



        //Provide the name of the num in ones
        switch (digit_at_one_place){

            case 1:
                System.out.print("One");
                break;
            case 2:
                System.out.print("Two");
                break;
            case 3:
                System.out.print("Three");
                break;
            case 4:
                System.out.print("Four");
                break;
            case 5:
                System.out.print("Five");
                break;
            case 6:
                System.out.print("Six");
                break;
            case 7:
                System.out.print("Seven");
                break;
            case 8:
                System.out.print("Eight");
                break;
            case 9:
                System.out.print("Nine");
                break;
        }

        if (num == 0) System.out.println("Zero");
        System.out.println();
    }

    System.out.println();


    int firstDigit = num % 10;//firstDigit:8   if num3568
    int remainingNumber = num / 10;// /remainingNumber: 356
    int SecondDigit = remainingNumber % 10;//Second digit 6
    remainingNumber = remainingNumber / 10;//remainingNumber: 35
    int thirdDigit = remainingNumber % 10;//third digit 5
    remainingNumber = remainingNumber / 10;// remainingNumber: 35
    int fourthDigit = remainingNumber % 10;//fourth digit: 3
    int sum = thirdDigit + SecondDigit + firstDigit + fourthDigit;
    System.out.println("The sum of all digits in " + num + " is " + sum);
5 Likes