Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Complete Question Text: Write a method called evenNumbers that accepts a Scanner

ID: 3767724 • Letter: C

Question


Complete Question Text:
Write a method called evenNumbers that accepts a Scanner reading input from a file with a series of integers, and report various statistics about the integers to the console. Report the total number of numbers, the sum of the numbers, the count of even numbers and the percent of even numbers. For example, if the input file contains the following text: 
5 7 2 8 9 10 12 98 7 14 20 22

Then the method should produce the following console output:

12 numbers, sum = 214

8 even (66.67%)

Explanation / Answer

Solution:

package com.chegg.nancy.solutions;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class EvenCount {

   public static void main(String[] args) {
      
       File text = new File("F://file.txt");
       Scanner scan;
       int count = 0;
       int evenCount = 0;
       int sum = 0;
       float percent;
       try {
           //Provide the file path to scanner
           scan = new Scanner(text);

           while (scan.hasNextLine()) {
               count++;
               int num = scan.nextInt();
               if (num % 2 == 0) {
                   evenCount++;
               }
               sum = sum + num;
           }
           //All printing and calculation goes here.
           percent = (evenCount / (float) count) * 100;
           System.out.println(count + " numbers" + ",sum = " + sum);
           System.out.println(evenCount + " even" + "(" + percent + "%)");

       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
   }
}

Output:

12 numbers,sum = 214
8 even(66.66667%)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote