Class Average Methods, and array - java

This is the prompt that I'm asked to follow.
Write a method called average that takes in an array of test grades and returns the letter grade
of the class average.
The grade ranges are as follows:
average >= 90 -> A
80 <= average < 90 -> B
70 <= average < 80 -> C
60 <= average < 70 -> D
average < 60 -> F
Use the following method header: public static char average(int[] grades)
This is the output example I'm supposed to follow.
How many grades do you want to enter? 10
Enter grade 1: 70
Enter grade 2: 87
Enter grade 3: 95
Enter grade 4: 80
Enter grade 5: 80
Enter grade 6: 78
Enter grade 7: 85
Enter grade 8: 90
Enter grade 9: 66
Enter grade 10: 89
The class average for the test is: B
This is what I have so far but I don't know how to include the method header stated above. public static char average(int[] grades)
import java.util.Scanner;
public class ClassAverage{
//Main Method
public static void main(String[] args){
//Variables
char average;
int i;
int sum = 0;
int b;
Scanner scan = new Scanner(System.in);
System.out.print("How many grades do you want to enter: ");
int grades = scan.nextInt();
int array[] = new int[grades];
for(i = 0;i < grades; i++){
System.out.print("Enter grade " + (i + 1) + ": ");
array[i] = scan.nextInt();
sum = sum + array[i];
}
b = sum / array.length;
if(b >= 90)
average = 'A';
else if(b <= 90 && b >= 80)
average = 'B';
else if(b <= 80 && b >= 70)
average = 'C';
else if(b <= 70 && b >= 60)
average = 'D';
else if(b <= 60)
average = 'F';
else
average = '?';
System.out.println("The class average for the test is: " + average);
}
}

public class MainClass {
//Main Method
public static void main(String[] args) {
//Variables
char avg;
int i;
Scanner scan = new Scanner(System.in);
System.out.print("How many grades do you want to enter: ");
int grades = scan.nextInt();
int array[] = new int[grades];
for (i = 0; i < grades; i++) {
System.out.print("Enter grade " + (i + 1) + ": ");
array[i] = scan.nextInt();
}
avg = average(array);
System.out.println("The class average for the test is: " + avg);
}
private static char average(int[] array) {
final int sum = Arrays.stream(array).sum();
final int b = sum / array.length;
if (b >= 90) {
return 'A';
} else if (b <= 90 && b >= 80) {
return 'B';
} else if (b <= 80 && b >= 70) {
return 'C';
} else if (b <= 70 && b >= 60) {
return 'D';
} else if (b <= 60) {
return 'F';
} else {
return '?';
}
} }
See that i accepted all the marks into an array and passed that int array into a method where i calculated the sum and grade and returned grade

Your instructor wants you to create a method called average that could be called from within main.
Essentially, all you need to do to complete the assignment is wrap your code inside of that method. So main would call average having passed in the ints to it.

I've written some pseudocode to help you take the code you have now and encapsulate it in the method you are requesting.
You already have the pieces written, you just need to move them from your main method to this new average method and make any necessary changes that come with changing scope (declaring or renaming certain variables in the new method).
Then to get the desired output you can call the method from within main by using average(gradeArray) and using the char value returned in a print statement.
public static char average(int[] gradeArray) {
// Find the sum of grades in gradeArray
// Use this sum and the size of the array to compute the average
// Use logic to determine which letter grade to print out based on the average
// Return the average
}

It is very simple code. My answer is
import java.util.Scanner;
public class AverageMethod {
public static void main(String[] args) {
char average;
int i;
int sum = 0;
int b;
Scanner scan = new Scanner(System.in);
System.out.print("How many grades do you want to enter: ");
int grades = scan.nextInt();
int array[] = new int[grades];
for(i = 0;i < grades; i++){
System.out.print("Enter grade " + (i + 1) + ": ");
array[i] = scan.nextInt();
sum = sum + array[i];
}
b = sum / array.length;
if(b<=100 && b>=0){
if(b<=100 && b >= 90)
average = 'A';
else if(b >= 80)
average = 'B';
else if(b >= 70)
average = 'C';
else if(b >= 60)
average = 'D';
else
average = 'F';
System.out.println("The class average for the test is: " + average);
}else{
System.out.println("Not in range");
}
}
}
I am also add my github uploaded coed for you. If you have any trouble please follow my githublink. Please study it for more clarification.

Another solution:
package test163;
import java.util.Scanner;
public class ClassAverage {
//Main Method
public static void main(String[] args) {
//Variables
char average;
int i;
int b;
Scanner scan = new Scanner(System.in);
System.out.print("How many grades do you want to enter: ");
int grades = scan.nextInt();
int array[] = new int[grades];
for (i = 0; i < grades; i++) {
System.out.print("Enter grade " + (i + 1) + ": ");
array[i] = scan.nextInt();
}
average = average(array);
System.out.println("The class average for the test is: " + average);
}
public static char average(int[] grades) {
int sum = 0;
for (int grade: grades) {
sum += grade;
}
int b = sum / grades.length;
if (b >= 90) {
return 'A';
} else if (b >= 80) {
return 'B';
} else if (b >= 70) {
return 'C';
} else if (b >= 60) {
return 'D';
} else {
return 'F';
}
}
}

Related

How can I get my print statement to work to where it prints the average score and the correlating letter grade?

public static void main(String[] args)
{
// Defining the constants for min and max range
final int minValue = -1;
final int maxValue = 100;
String message = "Welcome to Simple Gradebook!";
promptForInt(message, minValue, maxValue);
// Declaring variables for the loop & the sentinel variable
int score = 0;
boolean doneYet = false;
do
{
// Input Validation
if (score < minValue || score > maxValue)
{
System.err.printf("Invalid value. The acceptable range is"
+ " between %d and %d\n"
+ "Please try again\n", minValue, maxValue);
}
else
{
doneYet = true;
}
} while (doneYet == false);
}
public static int promptForInt(String message, int minValue, int maxValue)
{
// Declaring variables for the loop & the sentinel variable
int sum = 0;
int numStudents = 0;
int score = 0;
System.out.println(message);
//Creating the sentinel loop
do
{
System.out.printf("Enter the score for student #%d"
+ "(or -1 to quit): ", numStudents);
Scanner keyboard = new Scanner(System.in);
score = Integer.parseInt(keyboard.nextLine());
if (score != -1)
{
sum += score;
numStudents += 1;
}
} while (score != -1);
double avgScore = (double) sum / numStudents;
//Passing method to this method to convert grade to letter
convertToLetter(avgScore);
System.out.println("The average score is: " + avgScore
+ " which equates to a " + avgScore);
return 0;
}
public static char convertToLetter(double avg)
{
char avgScore = 0;
// Identifying the ranges for the grade letter
if (avgScore >= 90)
{
System.out.println("A");
}
else if (avg >= 80)
{
System.out.println("B");
}
else if (avg >= 70)
{
System.out.println("C");
}
else if (avg >= 60)
{
System.out.println("D");
}
else
{
System.out.println("F");
}
return avgScore;
}
}
How can I get my print statement to work to where it prints the average score and the correlating letter grade? Like this... “The average score is 90.5, which equates to an A”
My input validation is not working like it should for some reason. If a number lower that -1 or higher than 100 is entered, it should give the error message and begin the loop again.
You are not assigning and returning the grade letter from the function, convertToLetter correctly.
You are not printing the return value of the function, convertToLetter.
Write the function as shown below:
public static char convertToLetter(double avg) {
char gradeLetter;
// Identifying the ranges for the grade letter
if (avg >= 90) {
gradeLetter = 'A';
} else if (avg >= 80) {
gradeLetter = 'B';
} else if (avg >= 70) {
gradeLetter = 'C';
} else if (avg >= 60) {
gradeLetter = 'D';
} else {
gradeLetter = 'F';
}
return gradeLetter;
}
and then change the print statement as System.out.println("The average score is: " + avgScore + " which equates to a " + convertToLetter(avgScore));
You’re not doing anything with the result of convertToLetter(avgScore).
Assign the result to a variable:
char grade = convertToLetter(avgScore);
Then refer to that variable when printing:
System.out.println("The average score is: " + avgScore
+ " which equates to a " + grade);
—--
You have a similar problem when calling promptForInt(message, minValue, maxValue); you need to assign the result to a variable:
score = promptForInt(message, minValue, maxValue);
Another major bug you have is your input checking code. If score is not in range, your do while loop will loop infinitely because the value of score is not changed anywhere inside the loop.
Add this line after printing the error message:
score = promptForInt(message, minValue, maxValue);
—--
In general, you must realise that variables have scope. You assigning a value to the avgScore variable declared inside the convertToLetter method has no effect whatsoever on the variable of the same name declared in your main method - they are different variables, whose scope is limited to the method in which they are declared.
This code works. Explanations after.
import java.util.Scanner;
public class Calculat {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Defining the constants for min and max range
final int minValue = -1;
final int maxValue = 100;
String message = "Welcome to Simple Gradebook!";
System.out.println(message);
// Declaring variables for the loop & the sentinel variable
int score = 0;
int sum = 0;
int numStudents = 0;
while (true) {
score = promptForInt(keyboard, (numStudents + 1), minValue, maxValue);
if (score == -1) {
break;
}
sum += score;
numStudents++;
}
if (numStudents == 0) {
System.out.println("No data received.");
}
else {
double avgScore = (double) sum / numStudents;
char letter = convertToLetter(avgScore);
System.out.printf("The average score is: %.3f which equates to a %c%n",
avgScore,
letter);
}
}
public static int promptForInt(Scanner keyboard, int numStudent, int minValue, int maxValue) {
// Declaring variables for the loop & the sentinel variable
int score = 0;
boolean isValidScore = false;
// Creating the sentinel loop
do {
System.out.printf("Enter the score for student #%d (or -1 to quit): ", numStudent);
String line = keyboard.nextLine();
try {
score = Integer.parseInt(line);
if (score < minValue || score > maxValue) {
System.out.printf("Invalid value. Acceptable range is between %d and %d%n",
minValue,
maxValue);
}
else {
isValidScore = true;
}
}
catch (NumberFormatException xNumberFormat) {
System.out.printf("Not a number: %s%n", line);
}
} while (!isValidScore);
return score;
}
public static char convertToLetter(double avg) {
char avgScore = 0;
// Identifying the ranges for the grade letter
if (avg >= 90) {
avgScore = 'A';
}
else if (avg >= 80) {
avgScore = 'B';
}
else if (avg >= 70) {
avgScore = 'C';
}
else if (avg >= 60) {
avgScore = 'D';
}
else {
avgScore = 'F';
}
return avgScore;
}
}
Method promptForInt() should accept a single score from the user and return it. It should return only a valid score.
Method main() contains the loop for gathering up all the scores.
You need to check that at least one score was entered, otherwise you can't calculate the average.
Method convertToLetter() was always assigning the value zero to avgScore, essentially making avgScore the null character.
Here is a sample run of the program.
Welcome to Simple Gradebook!
Enter the score for student #1 (or -1 to quit): 66
Enter the score for student #2 (or -1 to quit): 66
Enter the score for student #3 (or -1 to quit): 68
Enter the score for student #4 (or -1 to quit): -1
The average score is: 66.667 which equates to a D

How to make while loop check if there are 16 digits in a string

How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!
import java.util.Scanner;
public class LuhnAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine();
int i = 0;
char chk = nums.charAt(15);
while(!nums .equals("") ) {
if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
}
int sum = 0;
for( i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if ( i % 2 == 0 ) {
num = num * 2;
if ( num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if ( sum2 == chk2) {
System.out.println("Number is valid.");
}
else {
System.out.println("Number is not valid. ");
}
System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
nums = input.nextLine();
}
System.out.println("Goodbye!");
input.close();
}
}
You can include your code that you only want done if the length ==16 in an if statement.
Meaning, instead of:
if (nums.length != 16) {
//code if there is an error
}
//code if there is no error
you can do:
if (nums.length == 16) {
//code if there is no error
} else {
//code if there is an error
}
(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine().trim();
if (nums.length() == 0) {
break; //exits while loop
}
if (nums.length() != 16) { //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
continue; //goes back to the beginning right away
}
//still here, process the number
char chk = nums.charAt(15);
int sum = 0;
for (int i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if (i % 2 == 0) {
num = num * 2;
if (num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if (sum2 == chk2) {
System.out.println("Number is valid.");
} else {
System.out.println("Number is not valid. ");
}
}
System.out.println("Goodbye!");
input.close();
}
}

How do I pass an array into a method to convert a double to a string?

enter image description hereI'm working on the convertToLetterGrade portion. I'd like to figure out how to pass my array into the string in order to output the minimum and maximum grade as a letter, the comments here are helpful, and I also need the gpa passed through in order to output a letter grade for that as well
public class WesternGPACalc {
public static void main(String[] args) {
//TODO:
//declare an array to hold the grades you earned in your classes
//feel free to use fake values
//declare at least 4 grades
//use a 0.0 - 4.0 scale...
//4.0 = A, 3.5 = A/B
//3.0 = B, 2.5 = B/C
//2.0 = C
//1.0 = D
//0.0 = F
//for example...
double[] grade = new double[4];
grade[0] = 4.00; // A
grade[1] = 2.50; // B/C
grade[2] = 2.00; // C
grade[3] = 1.00; // D
//TODO:
//use a method to print the min and max grades as letter grades
//printGradeStats(grade);
printGradeStats(grade);
//TODO:
//declare an array to hold the credits each class was worth
//the indices must match the grade[i] indices for the class
//for example...
int[] credit = new int[4];
credit[0] = 3;
credit[1] = 3;
credit[2] = 3;
credit[3] = 3;
//TODO:
//use a method to calculate and print the GPA as both
//a number and a letter grade
//pass both the credit and grade arrays to the method
//printGPA(grade, credit);
printGPA(grade, credit);
}
//TODO:
//Finish this method which will accept an array of grades
//and print the min and max letter grade
private static void printGradeStats(double[] grade){
//TODO:
//First determine the min and max letter grade...
double minGrade = 0;
double maxGrade = 0;
for(int i = 0; i < grade.length; i++) {
if(grade[i] < minGrade) {
minGrade = grade[i];
}
if(grade[i] > maxGrade) {
maxGrade = grade[i];
}
}
//TODO:
//convert the min and max grades to a letter grade...
//using your convertToLetterGrade(grade) method
//For example...
//String maxLetterGrade = convertToLetterGrade(maxGrade);
String maxLetterGrade = convertToLetterGrade(maxGrade);
String minLetterGrade = convertToLetterGrade(minGrade);
//TODO:
//Output them...
System.out.println("Max grade earned in a class was " + maxLetterGrade);
System.out.println("min grade earned in a class was " + minLetterGrade);
}
//TODO:
//Finish this method which will convert
//a grade on the 4.0 scale and return a letter grade
//Use the following scale...
//A = 4.0
//4.0 > A/B >= 3.5
//3.5 > B >= 3.0
//3.0 > B/C >= 2.5
//2.5 > C >= 2.0
//2.0 > D >= 1.0
//F < 1.0
private static String convertToLetterGrade(double grade){
String letterGrade = "F";
return letterGrade;
}
//TODO:
//Finish this method which will accept an array of grades and credits
//and print the cumulative GPA as a letter grade
private static void printGPA(double[] grade, int[] credit){
//Recall...GPA is just a weighted average...
//Cumulative GPA is the sum of all grade points -- grade[i] * credit[i]
//divided by the sum of all credits[i]
double sumCredits = 0;
//TODO:
//Calculate cumulative GPA
for (int n = 0; n < credit.length; n++) {
sumCredits += credit[n];
}
double gpa = ((grade[0] * credit[0]) + (grade[1] * credit[1]) + (grade[2] * credit[2]) + (grade[3] * credit[3])) / sumCredits;
//TODO:
//Output Cumulative GPA as both a number and a grade
System.out.println("Cumulative GPA " + gpa);
System.out.println("Cumulative GPA as a letter grade: ");
}
}
you can achieve it by using if-else block as following
private static String convertToLetterGrade(double grade){
String letterGrade="";
if(grade == 4.0){
letterGrade="A";
}else if(grade >=3.5 && grade < 4){
letterGrade="A/B";
}else if(grade >= 3.0 && grade < 3.5){
letterGrade="B";
}else if(grade >= 2.5 && grade < 3.0){
letterGrade="B/C";
}else if(grade >= 2.0 && grade < 2.5){
letterGrade="C";
}else if(grade >= 1.0 && grade < 2.0){
letterGrade="D";
}else if(grade < 1.0){
letterGrade="F";
}
return letterGrade;
}
I see you have an answer, but let me enhance the code a little bit.
When you are calculating the cumulative GPA, You hard code the summation. You can actually use the same loop you have used to get the sumCredits for that, and it is the correct way to do it (Otherwise you can only check/consider 4 elements/grades).
double gpa = 0.0;
for (int n = 0; n < credit.length; n++) {
gpa += grade[n] * credit[n];
sumCredits += credit[n];
}
gpa /= sumCredits;
One thing in Logic,
double minGrade = 5.0; // Or any max value, because you are going to find minimum values that this default one
double maxGrade = 0;
for(int i = 0; i < grade.length; i++) {
if(grade[i] < minGrade) {
// if you set `double minGrade = 0` this if never becode true since every grade is greater than `0`
minGrade = grade[i];
}
if(grade[i] > maxGrade) {
maxGrade = grade[i];
}
}

How can I get my user inputted numbers to be read all on one line to be placed into a 2D array?

Basically, I have this program. It is not completed yet but the gist of it is that it is a grade book with user input grades for a number of students they enter. They also enter the number of grades. What I'm struggling with is how to get the program to read the numbers after the first one on the line. The numbers being read is under the name "scores". So I want it to read it as:
1 2 3 4 (it just would read 1 and 5 right now)
5 6 7 8 (I want it to read them all)
Here's my code if it helps:
import java.util.Scanner;
import java.text.DecimalFormat;
public class SeventhAssignment {
public static double scores[][];
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat(".00");
Scanner input = new Scanner(System.in);
int students;
System.out.print("Enter number of students");
students = input.nextInt();
if (students <= 0) {
System.out.println("Both numbers must be positive");
System.exit(0);
}
int grades;
System.out.print("Enter number of grades");
grades = input.nextInt();
if (grades <= 0) {
System.out.println("Both numbers must be positive");
System.exit(0);
}
double[][] arr = new double[students][grades];
System.out.println("Enter " + students * grades + " grades: ");
int i;
int j;
for (i = 0; i < students; i++) {
for (j = 0; j < grades; j++) {
Scanner scores = new Scanner(System.in);
arr[i][j] = scores.nextInt();
}
for (i = 0; i < students; i++) {
for (j = 0; j < grades; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
public double getMinimum() {
double lowGrade = scores[0][0];
for (double studentGrades[] : scores) {
for (double grade : studentGrades) {
if (grade < lowGrade)
lowGrade = grade;
}
}
return lowGrade;
}
public double getMaximum() {
double highGrade = scores[0][0];
for (double studentGrades[] : scores) {
for (double grade : studentGrades) {// if grade is greater than
// higherGrade, assign to higher
// grade
if (grade > highGrade)
highGrade = grade;
}
}
return highGrade;// returtn higher grade
}
public static double getAverage(double setofGrades[]) {
double total = 0;// Initializing total
// sum of grade for one student
for (double grade : setofGrades)
total += grade;
// return average of grade
return (double) total / setofGrades.length;
}
public void outputGrades() {
System.out.println("The grades are:\n");
System.out.println(" ");// for alignment
for (double test = 0; test < scores[0].length; test++)
System.out.printf("Test %d", test + 1);
System.out.println("Average"); // student average column heading
for (double student = 0; student < scores.length; student++) {
System.out.printf("student %2d", student + 1);
for (double test : scores[(int) student])// output student grades
System.out.printf("%8d", test);
// call method getAverage to calculate students average grade
// pass row of grades as the argument to getAveerage
double average = getAverage(scores[(int) student]);
System.out.printf("%9.2f\n", average);
}
}
}
Thanks ahead for any help you guys can bring!

while loop - sum of even numbers and its average

http://pastebin.com/w8KntkE6#
package javaapplication9;
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication9 {
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
while (num >= 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0) {
count++;
sum += num;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
} else if (num % 2 != 0) {
continue;
}
System.out.println();
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
}
}
}
The code executes and it sums even numbers. However, when a odd number enters it returns an error or it breaks. I want it ignore any odd number. What is wrong with my code?
You continue the loop on odd numbers without modifying num - looks like it should infinite loop to me.
Am I missing something, or are you missing a nextInt() when you have an odd number? Since in the if even you have num = scan.nextInt();. You don't when num is odd.
Change
else if (num % 2 != 0){
continue;
}
to
else if (num % 2 !=0){
num = scan.nextInt();
continue;
}
just before continue statement add following code. I hope it will work correctly.
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
Change to:
package javaapplication9;
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication9 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
while (num >= 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0)
{
count++;
sum += num;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
num = scan.nextInt();
}
}
Try this. I'm not quite sure when do you want to print the average, you could move it out of the while loop if you want to print it at the end.
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
while ((num = scan.nextInt())> 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0){
count++;
sum += num;
System.out.println("The sum so far is " + sum);
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
System.out.print("Enter an integer (0 to quit): ");
}
System.out.println("end");
}
}

Categories