Write a method called printAverage that uses a sentinel-loop to repeatedly promp
ID: 3640272 • Letter: W
Question
Write a method called printAverage that uses a sentinel-loop to repeatedly prompt the user for numbers.Once the user types any number less than zero, the method should display the average of all nonnegative numbers typed.
Display the average as a double. Here is a sample dialogue with the user:
Type a number: 7
Type a number: 4
Type a number: 16
Type a number: -4
Average was 9.0
Note that the sentinel value in this example, (-4), is not included in the calculated average.
If the first number that the user types is negative, do not print an average: for example,
Type a number: -2
produces no output.
For starter I can think off these idea:
-counter variable
-double variable
-loop
-if statement
And this is what I wrote:
import java.util.*;
public class Testing {
public static void main(String[] args) {
printAverage(console);
}
public static void printAverage(double average, int sum)
{
Scanner console = new Scanner(System.in);
average = 0;
sum = 0;
System.out.println("Enter a number (negative number to quit): ");
int number = console.nextInt();
while (number > 0)
{
sum = sum + number;
System.out.print("Enter a number (negatives number to quit): ");
number = console.nextInt();
}
System.out.println("The average is: " + average);
}
}
I tried the codes but it gives me errors. Can anyone fix please and thank you!
BTW I'm using drjava-stable-20100913-r5387 .
Explanation / Answer
please rate - thanks
import java.util.*;
public class Testing {
public static void main(String[] args) {
printAverage( );
}
public static void printAverage()
{double average;
int sum,count=0;
Scanner console = new Scanner(System.in);
average = 0;
sum = 0;
System.out.println("Enter a number (negative number to quit): ");
int number = console.nextInt();
while (number > 0)
{count++;
sum = sum + number;
System.out.print("Enter a number (negatives number to quit): ");
number = console.nextInt();
}
average=(double)sum/count;
System.out.println("The average is: " + average );
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.