Here's the code for the Average class:
Source Code..
import java.util.Scanner;
class Average {
public static void
calculateAverage() {
Scanner input
= new Scanner(System.in);
System.out.print("Enter three numbers: ");
double num1 =
input.nextDouble();
double num2 =
input.nextDouble();
double num3 =
input.nextDouble();
double average
= (num1 + num2 + num3) / 3;
System.out.println("The average is " + average);
input.close();
}
}
Table of Contents:
Class: Average
Method: calculateAverage()
Inputs: None
Output: None
Description: This method prompts the user to enter three
numbers, calculates their average, and prints the result to the console. It
uses a Scanner object to read user input from the console. The close() method
is called on the Scanner object to release any system resources associated with
it.
To use this class, you can create an instance of the Average
class and call the calculateAverage() method:
public static void main(String[] args) {
Average avg = new
Average();
avg.calculateAverage();
}
When you run this code, it will prompt the user to enter
three numbers, calculate their average, and print the result to the console.
here are some additional points about the Average class:
The Scanner class is used to read user input from the
console. It takes System.in as its argument to indicate that input should be
read from the standard input stream.
The nextDouble() method is used to read the three numbers
entered by the user. This method reads the next token of input as a double
value.
The average is calculated by adding the three numbers
together and dividing by 3.
The System.out.println() method is used to print the average
to the console.
The close() method is called on the Scanner object to
release any system resources associated with it. This is good practice to
ensure that resources are not leaked.
Note that the calculateAverage() method is declared as
static. This means that it can be called without an instance of the Average
class. Therefore, you can call it directly from the main() method without first
creating an instance of the Average class.
When using the Scanner class, it is good practice to close
the scanner object once it is no longer needed. In this example, we close the
scanner after reading the input.
No comments:
Post a Comment