Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, on a line by itself, the sum of all the even integers read. Declare any variables that are needed. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input

Respuesta :

Answer:

Written in Java Programming Language

import java.util.Scanner;

public class Assign{

   public static void main(String [] args)    {

   Scanner stdin = new Scanner(System.in);

   int num,sum=0;

   System.out.println("Start Inputs: ");

   num = stdin.nextInt();

   while (num>=0) {

       if(num%2== 0)

       {

       sum+=num;    

       }      

       num = stdin.nextInt();

   }

   System.out.print("Sum of even numbers: "+sum);

   

   }

}

Explanation:

I'll start my explanation from line 4

This line initializes Scanner object stdin

Scanner stdin = new Scanner(System.in);

This line declares necessary variables and initializes sum to 0

   int num,sum=0;

This line prompts user for inputs

   System.out.println("Start Inputs: ");

This line reads user inputs

   num = stdin.nextInt();

This line checks is user input is not negative (It's a loop that will be repeated continually until a negative number is inputted)

   while (num>=0) {

This line checks if user input is an even number

       if(num%2== 0)

       {

If the above condition is true, this line calculates the sum of even numbers

       sum+=num;    

       }      

This line prepares the user for next input

       num = stdin.nextInt();

   }

This line prints the calculated sum of even number; If no even number is inputted, the sum will be 0

   System.out.print("Sum of even numbers: "+sum);