So I'm trying to define a counter in a while loop, and print it from the class:

public class odd
{
	public static void main(String[] args)
	{
		System.out.println("Input your number");
		int x = IO.readInt();
		
		int odd = 0;
		int even = 0;
		
		while (x != 0)
		{
			if (x % 2 !=0)
			{
				odd = odd++;
			}
			else
			{
				even = even++;
			}
			x = IO.readInt();
		}
		System.out.println(even + "evens" + odd + "odds");
	}
}

Anyone know how I can print the variables even and odd?

This program is attempting to take a continuous input of numbers from a user, and output the number of odds and evens:

We wish to develop a program that will count the number of even and odd integers in a set ("even" meaning divisible by 2, "odd" meaning not divisible by 2). We will use zero as an indicator that the set has been completely entered, and this zero should not be counted as part of the set. Ask the user for a sequence of integers, terminated by zero. Output the number even integers and the number of odd integers.

***IO is a module that we were provided with to read inputs and return errors***

Recommended Answers

All 4 Replies

import java.util.ArrayList;
import java.util.Collections;

public class odd {

    public static void main(String[] args) {
        int x = 20;
        ArrayList<Integer> odd = new ArrayList<Integer>();
        ArrayList<Integer> even = new ArrayList<Integer>();
        while (x > 0) {
            if (x % 2 != 0) {
                odd.add(x);
            } else {
                even.add(x);
            }
            x--;
        }
        Collections.sort(odd);
        Collections.sort(even);
        for (int i = 0; i < odd.size(); i++) {
            System.out.println(odd.get(i));
        }
        for (int i = 0; i < even.size(); i++) {
            System.out.println(even.get(i));
        }
        System.out.println(even + "evens" + odd + "odds");
    }

    private odd() {
    }
}

but if you don't understood,

just stupid questions,

how is validated Numeric value from input

what's int x = IO.readInt();

time to go sleep

no need for odd = odd++ or even = even++
here's the code with some few changes:
import java.util.Scanner;

public class odd
      {
    	  public static void main(String[] args)
      {
      System.out.println("Input your number");
      Scanner reader = new Scanner(System.in);
      int x = reader.nextInt();
      int odd = 0;
      int even = 0;
      while (x != 0)
      {
      if (x % 2 !=0)
      {
       odd++;
      }
      else
      {
       even++;
      }
      x = reader.nextInt();
      }
      System.out.println(even + " evens " + odd + " odds");
      }
      }
commented: Awesome help +1

Thank you both for your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.