caiusp caiusp - 2 years ago 137
Java Question

while and if iteration count X even numbers

im new to java and i can't figure it out how to write this program.

Write a program that given a set of numbers by input, sum them. After the 5th even number, stop it. Display the followed sum.

Ok i can check if a number its even and how to print the sum, but i can't understand how to check only 5 even numbers.
I tried with while iteration but don't know hot to write it using proper sintax.

import java.util.Scanner;
public class es04 {
public static void main(String[] args) {
Scanner scan = new Scanner(;
int n ;
int sum;
int even;
System.out.print("insert numbers: ");
n = scan.nextInt();

even = n % == 0; //dont know where to check even numbers, should it be inside while?
while (even=5) {
System.out.println("sum even numbers"+sum);

Answer Source

So what you want to be doing is continuously poll for numbers as long as your evenCount is less than five.

while(evenCount < 5) {
    int number = scan.nextInt();

You then want to check if the number you just got is even or not, and if it is increment your evenCount

if(number % 2 == 0) {

Regardless of if the number is even or not you want to add it to your sum.

sum += number;

You should be able to put together your homework from all of this now.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download