Finish the program below that uses a nested loop to compute the sum, product, an
ID: 3798115 • Letter: F
Question
Finish the program below that uses a nested loop to compute the sum, product, and average of rows of numbers given in input. The program will quit when the user inputs something that is not a number.
import java util. public class Lab5c public static void main (String args Scan the input Scanner scan [Your code here] Process each line separately If the next token is a double, assume there is an input line while (scan .hasNextDouble Get a line from the input String line [Your code here] Create a scanner for the line of input you have read Scanner linescan [Your code here] Write a while loop that will sum all of the double values on the line (hint: create double variables called "sum", product and "count". Set sum and count to 0, and product to 1 Then read as many double values as you can using the while loop When you read a number add it to sum, multiply product by it, and add 1 to count [Your code here] Compute the average by dividing sum by count [Your code here] Print out the sum, product, and average on one line [Your code here]Explanation / Answer
import java.util.*;
public class Lab5c
{
public static void main(String []args)
{
//Scan the input
Scanner scan = new Scanner(System.in);
//check if the next token in the input is a number or not
while(scan.hasNextDouble())
{
// If the token is a number, then scan the entire line
String line = scan.nextLine();
//Scan the line for the numbers
Scanner lineScan = new Scanner(line).useDelimiter("\s");
//initialize the variables
double sum = 0, product = 1, count = 0, average;
try{
//scan till the entire line from the input is read
while(lineScan.hasNext())
{
double value = lineScan.nextDouble();
sum = sum + value;
product = product * value;
count = count+1;
}
//calculate the average
average = sum/count;
//Print the sum, product and average values calculated above
System.out.println("Sum = "+ sum + "Product = "+ product + "average = " + average);
}
//it catches an exception whenever an input which is not a number is encountered in the line.
catch(Exception e)
{
System.out.println("Input which is not a number is found!! Please check.");
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.