intro to objected programing lecture recording on 12 March 2025 at 12.23.11 PM
Recap on Looping and User Input
Example Context: Creating a Java program to calculate the average of user-entered numbers.
Key Objectives
Ask the user to enter 10 numbers one at a time.
Calculate the average of these entered numbers.
Implementation Steps
**Define Scanner: ** Import the necessary scanner library:
import java.util.Scanner;
Initialize Variables:
Define an
accumulator
variable to hold the sum of entered grades.Define a
counter
variable to keep track of the number of inputs.
Loop Control with the while
Statement
Use a Counter Controlled Loop which will repeat for a specified number of times (in this case, 10).
Counter Variable: Set the
counter
to 1 to begin the count.Loop Condition: The loop will run while
counter <= 10
.
Inside the Loop
Use
System.out.print()
to request a numeric input from the user.Input Handling:
Use a method like
nextInt()
ornextDouble()
to read the user input.Add the entered number to the
total
accumulator.Increment the
counter
at each iteration to eventually exit the loop after 10 entries.
Average Calculation Logic
End Condition for Loop: The loop will stop automatically after 10 iterations.
To calculate the average:
After the loop completes, divide the total sum by 10 (or by the
counter
if dynamic).
Print the Average: Use
System.out.printf()
to format the output neatly.
Enhanced User Interaction
Dynamic Input: Instead of limiting entries to 10, allow users to enter as many values as they desire until they enter a sentinel value (e.g., -1 to indicate stopping).
Feedback Mechanism: Communicate prompts effectively:
Inform the user to enter a grade or -1 to stop.
Revised Loop Mechanism
While Loop for Continuous Entry:
Use a
while(true)
loop with a break condition for the sentinel value (-1):while (true) { System.out.print("Enter a grade or -1 to stop:"); grade = scanner.nextDouble(); if (grade == -1) break; total += grade; counter++; }
Handle Input Validations: Ensure that negative values do not affect the average calculation after users provide input:
Check for the condition of the grade before adjusting the total and counter.
Final Calculation
Final Average Calculation: Once the user chooses to stop:
Determine the average using the total sum and valid count of entries.
Implement logic to handle divisions carefully by ensuring the denominator is not zero.
Summary
By using this structured approach, you can create an interactive program that continuously asks for user input until they decide to stop, calculates the total, and finally computes the average of the entered grades.