1

I need to find the sum of all odd digits of user input numeric string. For example, if the input is 12235, the sum would be 1 + 3 + 5 = 9.

This is what my code looks like so far:

 import javax.swing.JOptionPane;
 public class sumOfAllOddDigits
 {
    public static void main( String[]args )
    {
      int a;
      int sum = 0;
      String userinput; 

      userinput = JOptionPane.showInputDialog( "Enter a number. " , null);

      a = Integer.parseInt(userinput);

      for (int i = 0; i <= a; i++)
      {
          if (i % 2 == 1)
          {
              sum += i;

          }

      }
      System.out.println( sum );
   }
}

The sum always prints a large number, but I do not know how to make it print the correct number. Please help. Thanks.

rostik612
  • 21
  • 1
  • 5
  • 2
    Youre not using a correct Logic here. Try writing the logic process on a paper before coding – Yassin Hajaj Oct 20 '15 at 20:49
  • 1
    `sum = userinput.chars().map(c -> c-'0').filter(d -> d % 2 == 1).sum()` – aioobe Oct 20 '15 at 20:52
  • possible duplicate http://stackoverflow.com/questions/3389264/how-to-get-the-separate-digits-of-an-int-number – Kick Buttowski Oct 20 '15 at 20:58
  • [`chars`](https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#chars--) gives you an [`IntStream`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html) of the characters in `userinput`. The [`IntStream.map`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#map-java.util.function.IntUnaryOperator-) transforms each character to it's ascii value minus `'0'` which means that `'0'` gets value `0`, `'1'` gets value `1` and so on... – aioobe Oct 20 '15 at 21:10
  • 1
    ...[`IntStream.filter`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#filter-java.util.function.IntPredicate-) will filter out the even numbers, and [`IntStream.sum`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#sum--) will sum up all the remaining numbers in the stream. – aioobe Oct 20 '15 at 21:10

5 Answers5

3

You are doing it wrong.

You do not add the digits, but all integers between 0 and it.

You use the userInput directly, iterate from 0 to userInput.length(), and use Integer.parseInt("" + userInput.charAt(i)) to parse the current digit.

Apart from this, the process is the same.

3

Right now you are finding the sum of all odd numbers between 0 and your input number.

Instead, you need to get each individual digit from the input number. The solution to that can be found here -- How to get the separate digits of an int number?

Then, for each digit, if the digit is odd, add it to a running sum.

Community
  • 1
  • 1
FriedSaucePots
  • 1,342
  • 10
  • 16
2

There's a nice way of doing this using Java 8 streams:

int sumOdds = userInput.chars().map(n -> n - '0').filter(n -> n % 2 == 1).sum();
sprinter
  • 27,148
  • 6
  • 47
  • 78
1

You can just check the string character by character, and add to the running sum if the current character represents an odd digit. Initially you were just find the sum of odd numbers between 0 and the number input by the user, that would obviously be incorrect.

userinput = JOptionPane.showInputDialog( "Enter a number. " , null);
for (int i = 0; i < userInput.length(); i++)
{
    char c = userInput.charAt(i);
    if ((c-'0') % 2 == 1)
    {
        sum += (c-'0');
    }
 }
 System.out.println( sum );

An alternative to doing arithmetic on characters would be to use the Character.digit(char, 10) it's easier to read, safer, and less error prone.

turingcomplete
  • 2,128
  • 3
  • 16
  • 25
0

How about this Code?

public static void main(String[] args) {
    System.out.println("Enter a number");
    Scanner scan = new Scanner(System.in);

    //Get number as an Integer(not string) More Precise
    Integer num = scan.nextInt();

    //Convert Integer to String
    String str = num.toString();

    //convert String to char array
    char[] chAr = str.toCharArray();        
    int sum = 0;
    for(int i=0;i<chAr.length;i++){


    //convert char array to integer inorder to verify 'if it is a odd number or not?'
    int a = Integer.parseInt(String.valueOf(chAr[i]));

    //if a is odd, then add 'a' to sum
    if(a%2==1) {
        sum = sum + a;
    }

    }

    System.out.println(sum);



}
Karthik Deepan
  • 144
  • 1
  • 8