Reputation: 45
I want to make a program that implements an array of numbers and if that array has an odd digit in it add it to the sum. For example 123(has 1 and 3 as odd digits) 222(no odd digits) and 434(has 3 as a odd digit). The end sum should be 123+434. This is what I came up with but the sum would be 123+123+434(Sice 123 has 2 odd numbers it counts it two times)
import java.util.Scanner;
public class Ex4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
System.out.print("Number of numbers: ");
int j = sc.nextInt();
System.out.println("List of numbers: ");
int arr[] = new int[j];
for(int i = 0; i < j; i++){
arr[i] = sc.nextInt();
}
for(int i = 0; i < j; i++)
{
int num = arr[i];
while (num > 0) {
System.out.println(num % 10);
if (num%2!=0)
{
sum= sum+arr[i];
System.out.println("SUM IS: "+sum);
}
num = num / 10;
}
}
}
}
Upvotes: 2
Views: 398
Reputation: 6549
If you don't want to add the same number multiple times, just break
out of the while
loop as soon as you add it the first time.
while (num > 0) {
System.out.println(num % 10);
if (num%2!=0)
{
sum = sum+arr[i];
System.out.println("SUM IS: "+sum);
break; // add this line
}
num = num / 10;
}
The break
statement immediately ends the loop it is inside of (regardless if it is a for
, while
or a do ... while
loop).
There is also a continue
statement (which you don't need here), that immediately continues to the next loop iteration, skipping the execution of any code after the continue
statement that is part of the loop.
Upvotes: 1