0% found this document useful (0 votes)
11 views2 pages

Calculate Average of Three Numbers

The document contains a Java program that defines a class named 'Average' which includes a method to calculate and print the average of three user-input numbers. The program prompts the user to enter three integers, calculates their average, and displays the result. It also includes necessary imports and a main method to execute the program logic.

Uploaded by

Dillibabu G
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Calculate Average of Three Numbers

The document contains a Java program that defines a class named 'Average' which includes a method to calculate and print the average of three user-input numbers. The program prompts the user to enter three integers, calculates their average, and displays the result. It also includes necessary imports and a main method to execute the program logic.

Uploaded by

Dillibabu G
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Q.

3 Print the average of three numbers entered by user by creating a class named 'Average' having a
method to calculate and print the average.

import [Link];

class Average {

// Method to calculate and print the average

void calculateAverage(int num1, int num2, int num3) {

int sum = num1 + num2 + num3;

double average = sum / 5.0; // Calculate the average

[Link]("The average is: " + average);

// Main method

public static void main(String[] args) {

// Create a Scanner object to take input from the user

Scanner scanner = new Scanner([Link]);

// Prompt the user to enter three numbers

[Link]("Enter the first number:");

int num1 = [Link]();

[Link]("Enter the second number:");

int num2 = [Link]();

[Link]("Enter the third number:");

int num3 = [Link]();


// Create an object of the Average class

Average averageCalculator = new Average();

// Call the calculateAverage method

[Link](num1, num2, num3);

// Close the scanner

[Link]();

Common questions

Powered by AI

To modify the program to handle floating-point inputs, the method calculateAverage could be updated to accept double instead of int as its parameters, e.g., calculateAverage(double num1, double num2, double num3). Additionally, the Scanner should use scanner.nextDouble() instead of scanner.nextInt() to read user inputs. This change enables the program to process both integer and decimal numbers, thus providing more precision in calculating the average for real number inputs .

Implementing functionality to specify the number of inputs dynamically would increase the program's flexibility by accommodating varying counts of input numbers to average, making it more versatile. This could be achieved by using an array or list to collect inputs and then iterating over this collection to compute the sum. This approach supports variability in input size and could be particularly useful in data analysis contexts where the number of datapoints isn't constant. This dynamic feature could also enhance the program’s scalability and user utility .

The use of the Java Scanner class in this context serves as an interface between user input and program execution by facilitating the capture of user-provided data from the console. This interaction allows the program to dynamically accept inputs at runtime that influence the execution path, namely through the compute step in calculateAverage, demonstrating a fundamental component of interactive console applications in Java .

The static main method is essential in Java programs as it serves as the entry point, allowing for the JVM to invoke it without needing an instance of the class. This choice influences the execution flow by making it procedural in nature, as all operations begin and can be orchestrated from within this method. As for design constraints, it restricts the use of non-static variables or methods directly, necessitating a more careful design for calling instance methods, as seen with the Average class instantiation to call calculateAverage. This static context reinforces certain architectural decisions, potentially leading to a less flexible design if not managed properly .

Not closing the Scanner object can lead to resource leaks, particularly with system resources like input streams. In the provided code, the Scanner object is closed using scanner.close(), which is a good practice to free up resources once they are no longer needed. Closing the scanner helps avoid potential memory leaks and ensures that resources are efficiently managed, even in small programs .

Even in simple programs like the one provided, using classes and methods enhances modularity and reusability. It allows the programs to be easily extended or modified without affecting other parts of the code. In this case, using a class like 'Average' and a method like 'calculateAverage' prepares the program for potential enhancements, such as adding additional mathematical functions or input validation features in the future. This structure supports object-oriented principles, promoting better organization and readability .

The code structure in the given Java program exemplifies procedural programming by sequentially organizing tasks into an input-process-output scheme. It begins with user input collection, followed by calculations performed in a distinct function (calculateAverage), and concludes with output display. This procedural flow ensures clarity and a linear execution path which is a hallmark of procedural programming, contrasting with more complex patterns found in functional or object-oriented paradigms .

The calculation of the average in the provided code can be corrected by changing the division from sum / 5.0 to sum / 3.0 to accurately reflect averaging three numbers instead of five. The current code incorrectly divides by 5.0, which results in a lower average value than the correct calculation. For instance, if the three entered numbers are 5, 10, and 15, the correct sum is 30, and the average should be 10 (30/3), not 6 (30/5).

The program does not currently include input validation, which is important for ensuring that the user inputs valid integers. Without validation, if a non-integer value is entered, the program will throw an InputMismatchException at runtime. This can be improved by including checks to confirm that the user enters valid numbers, potentially using a try-catch block, and prompting the user to re-enter values in case of invalid input .

Without error handling, if a user provides invalid input such as non-integer values, the program will crash, leading to a poor user experience. For a user-facing application, this lack of robustness can result in user frustration and decreased trust in the software's reliability. Implementing error handling via try-catch blocks captures and manages exceptions gracefully, allowing the program to continue running and prompting the user to supply valid inputs instead of abruptly terminating .

You might also like