HELP WITH FOOR LOOP
Got the right answer utilizig the while loop, but want to try differnt approach and with for loop and its not working
Before the continue keyword, i simply printed the output to see what was being printed... it seems only the last digit of enteredNum prints.
E.g.
input is :
4445
output will be :
5
5
5
5
Even: 0 Odd: 4
Here is my code:
public class Solution {
public static int even;
public static int odd;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int enteredNum = Integer.parseInt(reader.readLine());
int digit = 0;
// while (enteredNum > 0) {
// digit = enteredNum % 10;
// if (digit % 2 == 0) {
// even++;
// } else if (digit % 2 != 0) {
// odd++;
// }
// enteredNum /= 10;
// }
for (int i = enteredNum; i > 0; i /= 10) {
digit = enteredNum % 10;
if (enteredNum % 2 == 0) {
even++;
} else {
odd++;
}
System.out.println(digit);
continue;
}
System.out.println("Even: " + even + " Odd: " + odd);
}
}
I was thiking perhaps with the continue key word, it would move onto the next iteraition. and then carry out the last part of the for loop condition, i /= 10
My thinking :
1 - enteredNum (input) is 4445
2 - 4445 is larger than 0, go inside for loop
3 - in a seperate var called digit, carry ou enteredNum % 10 to get last digit
4 - use the if / else statement to determine if the digit is even or odd and add he respected counter
5 - use continue keyword to move onto next iteration
6 - take the 4445 input and now i /= 10, resulting in 444
7 - 444 > 0, go inside loop
8 - repeat process until 0 is no longer greater than 0
is there a flaw in the logic or is it a syntax issue.
Thanks in advance :)