In: Computer Science
JAVA:
Compute the average of a list of user-entered integers representing rolls of two dice. The list ends when 0 is entered. Integers must be in the range 2 to 12 (inclusive); integers outside the range don't contribute to the average. Output the average, and the number of valid and invalid integers (excluding the ending 0). If only 0 is entered, output 0. The output may be a floating-point value. Ex: If the user enters 8 12 13 0, the output is:
Average: 10 Valid: 2 Invalid: 1
Hints:
Use a while loop with expression (userInt != 0).
Read the user's input into userInt before the loop, and also at the end of the loop body.
In the loop body, use an if-else to distinguish integers in the range and integers outside the range.
For integers in the range, keep track of the sum, and number of integers. For integers outside the range, just keep track of the number.
Use a cast to get a floating-point output: (double) sum / num .
Whenever dividing, be sure to handle the case of the denominator being 0.
SOLUTION-
I have solve the problem in Java code with screenshot for easy
understanding :)
CODE-
//java code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new
Scanner(System.in);
int sum = 0;
int validCount = 0, invalidCount =
0;
float avg;
int userInt = scnr.nextInt();
while (userInt != 0) {
if (userInt
>= 2 && userInt <= 12) {
sum += userInt;
validCount++;
} else {
invalidCount++;
}
userInt =
scnr.nextInt();
}
if (validCount == 0) {
System.out.println("Average: 0");
} else {
avg = (float)
sum / validCount;
System.out.println("Average: " + avg + " Valid: " + validCount + "
Invalid: " + invalidCount);
}
scnr.close();
}
}
SCREENSHOT-
Sample output 1:
Sample output 2:
Sample output 3:
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------