Write a method named evenNumbers that accepts a Scanner as a parameter reading i
ID: 3560248 • Letter: W
Question
Write a method named evenNumbers that accepts a Scanner as a parameter reading input from a file containing a series of integers, and report various statistics about the integers. You may assume that there is at least one integer in the file. 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 a Scannerinput on file numbers contains the following text: then the call evenNumbers(input); should produce the following output:Explanation / Answer
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class Temps
{
static void evenNumbers(Scanner s)
{
String line = s.nextLine();
String numbers[] = line.split(" ");
int sum = 0;
int even = 0;
for (int i = 0; i < numbers.length; i++)
{
sum = sum + Integer.parseInt(numbers[i]);
if (Integer.parseInt(numbers[i]) % 2 == 0)
even ++;
}
System.out.println(numbers.length + " numbers, sum = " + sum);
System.out.println(even + " evens (" + (((double)even / numbers.length) * 100) + "%)");
}
public static void main(String[] args)
{
try
{
File text = new File("numbers.txt");
Scanner input = new Scanner(text);
evenNumbers(input);
}
catch (FileNotFoundException ie)
{
ie.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.