public static void main(String[] args) {
int sumEven = 0;
int sumOdd = 0;
Scanner scan = new Scanner(System.in);
// getting user's input
System.out.println("Enter the number:");
int num = scan.nextInt();
//converting int number to array
String a = Integer.toString(num);
int[] newNum = new int[a.length()];
for (int i=0; i<a.length(); i++){
newNum[i] = a.charAt(i);
}
// checking the element is even or odd
for (int i = 0; i<num; i++){
if (newNum[i] % 2 ==0){
sumEven = sumEven + newNum[i];
}else{
sumOdd = sumOdd + newNum[i];
}
}
// printing the output
System.out.println("Sum of Even Numbers: "+sumEven);
System.out.println("Sum of Odd Numbers: "+sumOdd);
}
num
as 25 so the array formed will be ['2', '5'] but in 2nd for loop you addednum
which is 25 and hence loop will run 25 times, so asnewNum
's length is only 2 (['2', '5']) it would go out of bounds. – Viraj DnewNum
is notnum
. Do you know how to debug your code? – Abraint[] newNum = new int[a.length()]
toint[] newNum = new int[num]
asnum
integer user has entered – sanjeevRm