In Java write a program that asks the user to input a set of

In Java, write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, set its value to -100. Add all values and print the sum when the user is done entering data. You must use exception handling to detect that the input is not a number.

Solution

FloatSum.java

import java.util.InputMismatchException;
import java.util.Scanner;


public class FloatSum {

  
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.print(\"Enter number of floating point values: \");
       int n = scan.nextInt();
       float sum = 0f;
       float num = 0f;
       for(int i=0; i<n; i++){
           System.out.print(\"Enter a floating point number: \");
           try{
           num = scan.nextFloat();
           }catch(InputMismatchException e){
               num = - 100;
               scan.nextLine();
           }
           sum = sum + num;
          
       }
       System.out.println(\"Sum of all floating point values is: \"+sum);
   }

}

Output:

Enter number of floating point values: 5
Enter a floating point number: 200
Enter a floating point number: 100
Enter a floating point number: 300.3
Enter a floating point number: e
Enter a floating point number: 200
Sum of all floating point values is: 700.3

In Java, write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, set its value to -100. A

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site