Trying to define predefined data type (overwrite)

3130 views java
5

I am new to java and working on a school assignment. When I run this program it gives an average of test scores but when I enter '999' to exit. It gives me an average number = 'NaN' but I need to have it say 0

import java.util.Scanner;

public class TestScoreApp {

    public static void main(String[] args) {
        // display operational messages
        System.out.println("Enter test scores that range from 0 to 100.");
        System.out.println("To end the program, enter 999.");
        System.out.println();  // print a blank line

        // initialize variables and create a Scanner object
        int scoreTotal = 0;
        int scoreCount = 0;
        int testScore = 0;
        Scanner sc = new Scanner(System.in);

        // get a series of test scores from the user
        while (testScore != 999) {
            // get the input from the user
            System.out.print("Enter score: ");
            testScore = sc.nextInt();

            // makes average score 0
            if (999 == testScore) {
                double averageScore;
            averageScore = 0;
        }
            // accumulate score count and score total
            if (testScore <= 100) {
                scoreCount = scoreCount + 1;
                scoreTotal = scoreTotal + testScore;
            } else
                System.out.println("Invalid entry: not counted"); 
        }


        // display the score count, score total, and average score

        double averageScore = (double) scoreTotal / scoreCount;
                if (averageScore == 0) {
                    System.out.println("0");
        } 
        String message = "\n"
                + "Score count:   " + scoreCount + "\n"
                + "Score total:   " + scoreTotal + "\n"
                + "Average score: " + averageScore + "\n";
        System.out.println(message);
    }
}

I've been working on this program for like 3 hours now and help would be greatly appreciated. Even a redirect to an archived post would be a great help.

answered question

1 Answer

13

If you enter 999 and your if statement is reached, it still won't stop average from being reassigned. (as the line double averageScore = (double) scoreTotal / scoreCount; is after the if statement.) If it is equal to 999 you want it to break so it will exit the loop:

if (999 == testScore) {
     double averageScore;
     averageScore = 0;
     break;
 }

posted this

Have an answer?

JD

Please login first before posting an answer.