Как найти произведение цифр числа в java

I need to find the sum and the product of the digits of the number entered. I have the sum part down but the only problem with it is that when I enter a number for the first time it gives me the right answer but when I enter another number, it just adds the sum of the first number and the sum of the second number together and then checks if the sum of the two sums is odd(sorry if its kind of confusing). For the product part of the code I just can’t seem to figure out how to do it.

Finally if the sum and the product both are odd I need it to say that the number entered is an Extremely odd number.

Here is the assignment:

This Java application checks whole numbers in the interval [101, 100001] to see if they are «extremely odd» and «super extremely odd» numbers.

A whole number is «extremely odd» if…

(0) it’s an odd number
(1) it has an odd number of digits
(2) all of its digits are odd numbers
(3) the sum of its digits is an odd number
(4) the product of its digits is an odd number

A «super extremely odd» number is an extremely odd number such that…

(5) all digits comprising the sum of its digits are odd numbers
(6) all digits comprising the product of its digits are odd numbers

Loop prompting the user to enter positive whole numbers. Looping ends when a -1 is entered. For each number entered, check to see if its extremely odd (or super extremely odd).

If somebody could just explain what the requirements for the super extremely odd numbers part are saying that would be appreciated because English is not my first language.
I don’t need anyone to do the whole assignment. I just need help on the parts that I’m stuck in. Thank you in advance!

public class TestOddNumbers {

  public static void main(String[] args) {

    Scanner stdin = new Scanner(System.in);
    int userInput;
    int sum = 0;
    int product = 1;
    final int EXIT = -1;
    final int MIN = 101;
    final int MAX = 100001;
    String total = "";

    do{
        System.out.println("Please enter a positive whole number between "
                + "" + MIN + " and " + MAX + ". Enter " + EXIT + " "
                + "when you are done entering numbers.");

        userInput = stdin.nextInt();
        total += String.valueOf(userInput);

        if(userInput==EXIT){
        System.out.println("Thanks for playing!");
        break;
        }

        if(userInput > MIN && userInput < MAX){
            if(userInput % 2 == 1){
            System.out.println("It's an odd number");
            }
            else{
                System.out.println("Not an odd number");
            }

            if(total.length() %2 == 1){
            System.out.println("It also has an odd number of digits");
            }
            else{
            System.out.println("Does not have an odd number of digits");
            }

            boolean[] allOdds = {true};

            String.valueOf(userInput).chars().forEach(i -> {
            if(Integer.parseInt(String.valueOf((char)i))%2==0){
            allOdds[0] = false;
            }
            });

            if(allOdds[0]){
                System.out.println("all digits are odds");
            }
            else{
                System.out.println("all digits are not odds");
            }

            // The sum code block
            while (userInput != 0) {
                sum += userInput % 10;
                userInput /= 10;
            }
            if((sum += userInput) % 2 == 1){
                System.out.println("The sum of the digits are odd");
            }
            else{
                System.out.println("The sum of the digits are not odd");
            }

            // The product code block
            while(userInput != 0) {
                product *= userInput % 10;
                userInput /= 10;
            }
            if((sum *= userInput) % 2 == 1){
                System.out.println("The product of the digits are odd");
            }
            else{
                System.out.println("The product of the digits are not odd");
            }

        }
        else{
            System.out.println("Check the bounds again!!");
        }

        System.out.println();
    } 
    while(userInput > MIN || userInput < MAX);

   }
}

1 / 1 / 0

Регистрация: 02.07.2011

Сообщений: 25

1

Найти сумму и произведение цифр трехзначного числа.

11.08.2012, 10:04. Показов 23176. Ответов 1


Студворк — интернет-сервис помощи студентам

Дано трехзначное число. Найти сумму и произведение его цифр. На Java/



1



Alex_oo7

51 / 62 / 16

Регистрация: 18.10.2010

Сообщений: 240

11.08.2012, 19:03

2

Лучший ответ Сообщение было отмечено Сулейман как решение

Решение

Java
1
2
3
4
5
6
7
8
9
int n = 123;
int s = 0, m = 1;
for (int i = 0; i < 3; i++) {
    m *= n % 10;
    s += n % 10;
    n /= 10;
    }
System.out.println("Сумма: " + s);
System.out.println("Произведение: " + m);



2



Мне нужно найти сумму и произведение цифр введенного числа. У меня есть часть суммы, но единственная проблема с этим состоит в том, что, когда я ввожу число в первый раз, это дает мне правильный ответ, но когда я ввожу другое число, оно просто добавляет сумму первого числа и сумму второе число вместе и затем проверяет, является ли сумма двух сумм нечетной (извините, если это немного запутывает). Для части кода продукта я просто не могу понять, как это сделать.

Наконец, если сумма и произведение нечетны, мне нужно сказать, что введенное число является чрезвычайно нечетным числом.

Вот назначение:

Это Java-приложение проверяет целые числа в интервале [101, 100001], чтобы определить, являются ли они «чрезвычайно странными» и «супер чрезвычайно странными» числами.

Целое число «очень странно», если…

(0) это нечетное число (1) оно имеет нечетное число цифр (2) все его цифры являются нечетными числами (3) сумма его цифр является нечетным числом (4) произведение его цифр является нечетным число

«Супер чрезвычайно странное» число — чрезвычайно необычное число, такое что…

(5) все цифры, составляющие сумму его цифр, являются нечетными числами (6) все цифры, составляющие произведение его цифр, являются нечетными числами

Цикл, предлагающий пользователю ввести положительные целые числа. Цикл заканчивается, когда вводится -1. Для каждого введенного числа проверьте, не является ли он чрезвычайно странным (или сверхчетким).

Если бы кто-то мог просто объяснить, что говорится в требованиях, касающихся супер экстремальных нечетных чисел, это было бы полезно, потому что английский не мой родной язык. Мне не нужно, чтобы кто-то делал все задания. Мне просто нужна помощь по тем деталям, в которых я застрял. Заранее спасибо!

public class TestOddNumbers {

  public static void main(String[] args) {

    Scanner stdin = new Scanner(System.in);
    int userInput;
    int sum = 0;
    int product = 1;
    final int EXIT = -1;
    final int MIN = 101;
    final int MAX = 100001;
    String total = "";

    do{
        System.out.println("Please enter a positive whole number between "
                + "" + MIN + " and " + MAX + ". Enter " + EXIT + " "
                + "when you are done entering numbers.");

        userInput = stdin.nextInt();
        total += String.valueOf(userInput);

        if(userInput==EXIT){
        System.out.println("Thanks for playing!");
        break;
        }

        if(userInput > MIN && userInput < MAX){
            if(userInput % 2 == 1){
            System.out.println("It's an odd number");
            }
            else{
                System.out.println("Not an odd number");
            }

            if(total.length() %2 == 1){
            System.out.println("It also has an odd number of digits");
            }
            else{
            System.out.println("Does not have an odd number of digits");
            }

            boolean[] allOdds = {true};

            String.valueOf(userInput).chars().forEach(i -> {
            if(Integer.parseInt(String.valueOf((char)i))%2==0){
            allOdds[0] = false;
            }
            });

            if(allOdds[0]){
                System.out.println("all digits are odds");
            }
            else{
                System.out.println("all digits are not odds");
            }

            // The sum code block
            while (userInput != 0) {
                sum += userInput % 10;
                userInput /= 10;
            }
            if((sum += userInput) % 2 == 1){
                System.out.println("The sum of the digits are odd");
            }
            else{
                System.out.println("The sum of the digits are not odd");
            }

            // The product code block
            while(userInput != 0) {
                product *= userInput % 10;
                userInput /= 10;
            }
            if((sum *= userInput) % 2 == 1){
                System.out.println("The product of the digits are odd");
            }
            else{
                System.out.println("The product of the digits are not odd");
            }

        }
        else{
            System.out.println("Check the bounds again!!");
        }

        System.out.println();
    } 
    while(userInput > MIN || userInput < MAX);

   }
}

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Pick a username
Email Address
Password

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Мне нужно найти сумму и произведение цифр введенного числа. У меня есть часть суммы, но единственная проблема с ней заключается в том, что когда я ввожу число в первый раз, оно дает мне правильный ответ, но когда я ввожу другое число, оно просто добавляет сумму первого числа и сумму второе число вместе, а затем проверяет, является ли сумма двух сумм нечетной (извините, если это сбивает с толку). Для части кода продукта я просто не могу понять, как это сделать.

Наконец, если сумма и произведение нечетны, мне нужно сказать, что введенное число является чрезвычайно нечетным числом.

Вот задание:

Это Java-приложение проверяет целые числа в интервале [101, 100001], чтобы определить, являются ли они «чрезвычайно нечетными» и «сверхчрезвычайно нечетными» числами.

Целое число является «чрезвычайно нечетным», если…

(0) это нечетное число (1) оно имеет нечетное количество цифр (2) все его цифры нечетные числа (3) сумма его цифр является нечетным числом (4) произведение его цифр является нечетным количество

«Суперчрезвычайно нечетное» число — это чрезвычайно нечетное число, такое, что…

(5) все цифры, составляющие сумму его цифр, являются нечетными числами (6) все цифры, составляющие произведение его цифр, являются нечетными числами

Цикл, предлагающий пользователю ввести положительные целые числа. Цикл заканчивается, когда вводится -1. Для каждого введенного числа проверьте, не является ли оно чрезвычайно нечетным (или супер-чрезвычайно нечетным).

Если бы кто-нибудь мог просто объяснить, что говорят требования к части супер-чрезвычайно нечетных чисел, это было бы признательно, потому что английский не мой родной язык. Мне не нужно, чтобы кто-то выполнял все задание. Мне просто нужна помощь в части, в которой я застрял. Заранее спасибо!

public class TestOddNumbers {

  public static void main(String[] args) {

    Scanner stdin = new Scanner(System.in);
    int userInput;
    int sum = 0;
    int product = 1;
    final int EXIT = -1;
    final int MIN = 101;
    final int MAX = 100001;
    String total = "";

    do{
        System.out.println("Please enter a positive whole number between "
                + "" + MIN + " and " + MAX + ". Enter " + EXIT + " "
                + "when you are done entering numbers.");

        userInput = stdin.nextInt();
        total += String.valueOf(userInput);

        if(userInput==EXIT){
        System.out.println("Thanks for playing!");
        break;
        }

        if(userInput > MIN && userInput < MAX){
            if(userInput % 2 == 1){
            System.out.println("It's an odd number");
            }
            else{
                System.out.println("Not an odd number");
            }

            if(total.length() %2 == 1){
            System.out.println("It also has an odd number of digits");
            }
            else{
            System.out.println("Does not have an odd number of digits");
            }

            boolean[] allOdds = {true};

            String.valueOf(userInput).chars().forEach(i -> {
            if(Integer.parseInt(String.valueOf((char)i))%2==0){
            allOdds[0] = false;
            }
            });

            if(allOdds[0]){
                System.out.println("all digits are odds");
            }
            else{
                System.out.println("all digits are not odds");
            }

            // The sum code block
            while (userInput != 0) {
                sum += userInput % 10;
                userInput /= 10;
            }
            if((sum += userInput) % 2 == 1){
                System.out.println("The sum of the digits are odd");
            }
            else{
                System.out.println("The sum of the digits are not odd");
            }

            // The product code block
            while(userInput != 0) {
                product *= userInput % 10;
                userInput /= 10;
            }
            if((sum *= userInput) % 2 == 1){
                System.out.println("The product of the digits are odd");
            }
            else{
                System.out.println("The product of the digits are not odd");
            }

        }
        else{
            System.out.println("Check the bounds again!!");
        }

        System.out.println();
    } 
    while(userInput > MIN || userInput < MAX);

   }
}

2 ответа

public class Product_of_Digits_of_a_Number
{
    // accepting a three digit number
    static void calc(int n)
    {
        System.out.println("f"); // clearing the screen

        // extracting each digit from the number
        int units = n % 10; // taking the units' digit out of the number and storing in u

        int tens = (n / 10) % 10; //taking tens' digit and string in tens.

        int hundreds = (n / 10) / 10; //taking hundreds' digit and storing in hundreds

        // performing the required calculation on the digits
        int a = units * tens * hundreds; // storing the product in a

        // printing the digits
        System.out.println("the product of digits of " + n + " is " + a);
   }
}

Заметка

Если вам нужна сумма, код тот же, но вы должны сохранить сумму в переменной a.


1

stefanobaghino
8 Фев 2018 в 18:22

public class MyClass {
    static void myFun(int n)

    {
        int sum = 0;
        int prod = 1;
        while (n != 0)
        {
            sum = sum + n % 10;
            prod = prod * (n % 10);
            n = n / 10;
        }
        System.out.print("Product and Sum of digits of number given is:"+prod+" and " +sum);
    }
    public static void main(String[] a) {
        myFun(25);
    }
}

Источник


0

Joseph Samuel
1 Май 2022 в 19:22

Понравилась статья? Поделить с друзьями:
  • Как найти выражение функции распределения
  • Как найти в ворде знаки больше меньше
  • Как найти продавца форум
  • Как найти соседа затопил меня
  • Как найти развели или нет