Question

In: Computer Science

JAVA: This is my code, but when it runs, for the "Average Score" output, it only...

JAVA: This is my code, but when it runs, for the "Average Score" output, it only gives me NaN. How can I fix that?

import java.util.Scanner;

public class prog4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);

String name;
double score;
double minScore = 0;
double maxScore = 0;
int numberOfRecords = 0;
double sum = 0;
double average = sum / numberOfRecords;

System.out.printf("%-15s %-15s %-15s\n", "Student#", "Name", "Score");
  
       while (reader.hasNext()) {
name = reader.next();
score = reader.nextDouble();
sum += score;
System.out.printf("%8d%12s %16.2f\n", numberOfRecords + 1, name, score);
if (numberOfRecords == 0) {
minScore = score;
} else if (minScore > score) {
minScore = score;
}
if (maxScore < score) {
maxScore = score;
}
numberOfRecords += 1;
}

System.out.println("Number of Records: " + numberOfRecords);
System.out.printf("Max Score: %.2f\n", maxScore);
System.out.printf("Min Score: %.2f\n", minScore);
System.out.printf("Average Scores: %.2f\n", average);

}

}

Solutions

Expert Solution

Problem is with that average is being calculated before reading and processing scores. There is a need of change at two lines of code.

Modified lines are highlighted using BOLD case.

Update Program:

import java.util.Scanner;

public class prog4 {
   public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

        String name;
        double score;
        double minScore = 0;
        double maxScore = 0;
        int numberOfRecords = 0;
        double sum = 0;
        double average;

        System.out.printf("%-15s %-15s %-15s\n", "Student#", "Name", "Score");
      
        while (reader.hasNext()) {
            name = reader.next();
            score = reader.nextDouble();
            sum += score;
            System.out.printf("%8d%12s %16.2f\n", numberOfRecords + 1, name, score);
            if (numberOfRecords == 0) {
                minScore = score;
            } else if (minScore > score) {
                minScore = score;
            }
            if (maxScore < score) {
                maxScore = score;
            }
            numberOfRecords += 1;
        }
      
       average = sum / numberOfRecords;

        System.out.println("Number of Records: " + numberOfRecords);
        System.out.printf("Max Score: %.2f\n", maxScore);
        System.out.printf("Min Score: %.2f\n", minScore);
        System.out.printf("Average Scores: %.2f\n", average);
    }
}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

Sample Output:


Related Solutions

Here is my java code. It works and has the correct output, but I need to...
Here is my java code. It works and has the correct output, but I need to add a file and I am not sure how. I cannot use the FileNotFoundException. Please help! import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,0,0}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: "...
This is my code I want the average temp for the week to be printed when...
This is my code I want the average temp for the week to be printed when the user types : 'week' currently when the user types  'week' it only prints  Monday - Sunday and the average temp for each day. import java.util.Arrays; import java.util.ArrayList; import java.util.Scanner; public class weeklytemps {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);                  ArrayList Day = new ArrayList(Arrays.asList(    "Monday","Tuesday","Wednesday","Thurday","Friday","Saturday","Sunday")); // Stores days of the week...
Java Input, Output and for-loop function. Practice01) Write-an average SCORE application called TestScores01 This project reads...
Java Input, Output and for-loop function. Practice01) Write-an average SCORE application called TestScores01 This project reads in a list of integers as SCOREs, one per line, until a sentinel value of -1. After user type in -1, the application should print out how many SCOREs are typed in, what is the max SCORE, the 2nd max SCORE, and the min SCORE, the average SCORE after removing the max and min SCORE. When SCORE >= 90, the school will give this...
This is the code I have. My problem is my output includes ", 0" at the...
This is the code I have. My problem is my output includes ", 0" at the end and I want to exclude that. // File: main.cpp /*---------- BEGIN - DO NOT EDIT CODE ----------*/ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> using namespace std; using index_t = int; using num_count_t = int; using isConnected_t = bool; using sum_t = int; const int MAX_SIZE = 100; // Global variable to be used to count the recursive calls. int recursiveCount =...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is my first java homework so for you i don't think it will be hard for you. (basic stuff) the problem: Write a complete Java program The transport Company in which you are the engineer responsible of operations for the optimization of the autonomous transport of liquid bulk goods, got a design contract for an automated intelligent transport management system that are autonomous trucks which...
JAVA programming - please ONLY answer prompts with java code *Inheritance* will be used in code...
JAVA programming - please ONLY answer prompts with java code *Inheritance* will be used in code Classwork A zoo is developing an educational safari game with various animals. You will write classes representing Elephants, Camels, and Moose. Part A Think through common characteristics of animals, and write a class ZooAnimal. ☑ ZooAnimal should have at least two instance variables of different types (protected), representing characteristics that all animals have values for. ☑ It should also have at least two methods...
*****************PLEASE PROVIDE THE CODE IN RACKET PROGRAMMING LANGUAGE ONLY AND MAKE SURE CODE RUNS ON THE...
*****************PLEASE PROVIDE THE CODE IN RACKET PROGRAMMING LANGUAGE ONLY AND MAKE SURE CODE RUNS ON THE WESCHEME IDE************* Write a tail-recursive Racket function "kept-short-rec" that takes an integer and a list of strings as parameters and evaluates to an integer. The resulting integer should be the number of strings on the original list whose string length is less than the integer parameter. For example, (kept-short-rec 3 '("abc" "ab" "a")) should evaluate to 2 because there are only 2 strings shorter...
*****************PLEASE GIVE THE CODE IN RACKET PROGRAMMING ONLY AND MAKE SURE THE CODE RUNS ON WESCHEME...
*****************PLEASE GIVE THE CODE IN RACKET PROGRAMMING ONLY AND MAKE SURE THE CODE RUNS ON WESCHEME IDE*************** Write a recursive Racket function "keep-short-rec" that takes an integer and a list of strings as parameters and evaluates to a list of strings. The resulting list should be all of the strings from the original list, maintaining their relative order, whose string length is less than the integer parameter. For example, (keep-short-rec 3 '("abc" "ab" "a")) should evaluate to '("ab" "a") because...
*****************PLEASE GIVE THE CODE IN RACKET PROGRAMMING ONLY AND MAKE SURE THE CODE RUNS ON WESCHEME...
*****************PLEASE GIVE THE CODE IN RACKET PROGRAMMING ONLY AND MAKE SURE THE CODE RUNS ON WESCHEME IDE*************** Write a recursive Racket function "sum-diff" that takes two lists of integers that are the same length and evaluates to an integer. The resulting integer should be the sum of the absolute value of the differences between each pair of integers with the same index in the two lists. For example (sum-diff '(-1 -2 -3) '(1 2 3)) should evaluate to 12 because...
Trying to score a hand of blackjack in this python code but my loop is consistently...
Trying to score a hand of blackjack in this python code but my loop is consistently outputting (13,1) which makes me think that something is wrong with my loop. Could someone help me with this code?: import random cards = [random.randint(1,13) for i in range(0,2)] #initialize hand with two random cards def get_card(): #this function will randomly return a card with the value between 1 and 13 return random.randint(1,13) def score(cards): stand_on_value = 0 soft_ace = 0 for i in...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT