0

Why are the odd and even variables not increasing?

The output is still saying that odd and even are 0.

import java.util.Scanner;

public class RepeatingBreakingAndRemembering {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        System.out.println("Give numbers:");
        int sum = 0;
        int total = 0;
        double average = 0;
        int even = 0;
        int odd = 0;
        
        while (true) {            
            int number = Integer.valueOf(scanner.nextLine());
            if (number == -1) {
                System.out.println("Thx! Bye!");                
                break;                
            } 
            if  (number != -1) {                 
                sum += number;
                total++;
                average = (double)sum / (double)total;
                continue;
            }
            if (number % 2 == 0) {
                even++;     
            } else {
                odd++;
            }
        }
        System.out.println("Sum:" + sum);
        System.out.println("Numbers:" + total);
        System.out.println("Average:" + average);
        System.out.println("Even:" + even);
        System.out.println("Odd:" + odd);
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 4
    You need to look at what `continue` does. And also look into the difference of `if` and `if...else` – g00se Aug 09 '21 at 09:08
  • I think the `continue` is the problem. If `continue` is called none of the loop afterwards is done so you never get to the last `if-else`. See [here](https://www.w3schools.com/java/java_break.asp) for some examples. To extend to what g00se commented, look into `else if`. – bluejambo Aug 09 '21 at 09:08

2 Answers2

0
if (number % 2 == 0) {
   even++;
} else {
   odd++;
}

will never be executed because of continue. You need to get rid of it

g00se
  • 3,207
  • 2
  • 5
  • 9
0

Because there are two if judgments in the code. In this judgment, enter -1 to exit

   if (number == -1) {
       System.out.println("Thx! Bye!");                
       break;                
    } 

In another judgment, if you enter a number other than -1, it will continue, that is, continue to loop, and will not continue to judge whether it is odd or even

if  (number != -1) {                 
     sum += number;
     total++;
     average = (double)sum / (double)total;
     continue;
  }

You can change the second if judgment to this, so you can enter -1 to end the program, enter -2 (or other numbers less than -1) to count the average, and enter other numbers to count odd and even numbers

if  (number < -1) {                 
         sum += number;
         total++;
         average = (double)sum / (double)total;
         continue;
      }
xuanzjie
  • 51
  • 7