-1
import java.util.Scanner;
public class While
{
public static void main(String args[]){
    Scanner in = new Scanner(System.in);
    System.out.print("Choose a number to find various things for: ");
    int n = in.nextInt();
    // Extraneous variables to keep myself organized.
    int i = 0;
    int b = 1;
    int t = 0;
    int sum1 = 0;
    int sum2 = 0;
    double sum3 = 0;
    double total = 0;
    // Extraneous code to keep simple.
    System.out.println("Squares up until your number");
     while ( (i * i) < n ){
     System.out.println(i * i);
     sum1 = sum1 + (i * i);
     i++;
    }
    System.out.println("Now positives divisible by 10");
     while ( (b * 10) < n){
     System.out.println(b * 10);
     sum2 = sum2 + (b * 10);
     b++;
    }
    System.out.println("Now squares of 2!");
     while ( Math.pow(2,t) < n ){
     System.out.println(Math.pow(2,t));
     sum3 = sum3 + (Math.pow(2,t));
     t++;
    }
    // Second part of assignment.
    total = total + (sum1 + sum2 + sum3);
    System.out.println("The sum of all numbers: " + total);
    System.out.println();

}
}

Now, the total needs to be separated into its own numbers. If the user puts in the number 50, the program's total will be 303. How can I get that 303 to be, 3, 0, 3, then add only the odd numbers then use a simple System.out. to print a 6 for this example?

Zev Telvi
  • 1
  • 2
  • 1
    possible duplicate of [How to get the separate digits of an int number?](http://stackoverflow.com/questions/3389264/how-to-get-the-separate-digits-of-an-int-number) – RealSkeptic Sep 18 '15 at 12:20
  • @Zev... what you mean with odd numbers... sum if number is `3` and not if its `2`? or sum numbers in odd positions like `1`, `3`, `5` etc..? – Jordi Castilla Sep 18 '15 at 12:35

2 Answers2

1

Use modulus to get digit by digit. Check this answer to further explanation.

int sum = 0;
while (total > 0) {
    int digit = (int) total % 10;
    total = total / 10;
    if (digit % 2 != 0) sum += digit; 
}
System.out.println("The sum of all odd digits: " + sum);
System.out.println();   

OUTPUT for 50:

The sum of all numbers: 303.0

The sum of all odd digits: 6

OUTPUT for 200:

The sum of all numbers: 3170.0

The sum of all odd digits: 11
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0
int mod = 0, sum = 0;

while (total > 1) {
    mod = (int) (total % 10);
    total = total / 100;
    sum += mod;
}

System.out.println("The sum of odd numbers is " + sum);

I have used the modulus operator to get the mod. But as you need odd numbers, I divided total by 100 till it is greater than 1. Lower number of loops will run in this case.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109