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...
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...
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 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...
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...
Below is my code in C#, When I run it, the output shows System.32[], Can you...
Below is my code in C#, When I run it, the output shows System.32[], Can you please check and let me know what is the problem in the code. class Program { static void Main(string[] args) { int number=12; Console.WriteLine(FizzArray(number)); } public static int[] FizzArray(int number) { int[] array = new int[number]; for (int i = 1; i < number; i++) array[i] = i; return array; }
Please use Java Eclipse and show code/output Please create a program that determines when a good...
Please use Java Eclipse and show code/output Please create a program that determines when a good day to go to the beach is. Please use the users input and its returning output. If the weather is 70 degree or greater, the program should say yes it is a good day to go If the weather is less than 70 degrees to say no the weather is not a good day to go
What's wrong with my Python code. We have to find the regularexpression in Python My output...
What's wrong with my Python code. We have to find the regularexpression in Python My output should look like this My IP address 128. 0. 0. 1 My IP address 53. 20. 62. 201 My code ipAddresses = [] ipRegEx = re.compile(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")    result = myRegEx.find all(Search Text)    def Regular_expression(ipAddresses)       for i in ipAddresses:          print(i) ipSearchResult = ipRegEx.search(line)    if ipSearchResult != None and ipSearchResult.group() not in ipAddresses:       ipAddresses.append(ipSearchResult.group()) we have to use loop too.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT