Write a program in JAVA that asks the user to input a set of
Write a program in JAVA 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
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
boolean go = true;
float sum = 0;
Scanner in = new Scanner(System.in);
float f;
float a = -100;
while(true) {
try {
f = in.nextFloat();
sum = sum + f;
} catch(InputMismatchException e) {
in.nextLine(); /* handling invalid characters just entered by user*/
System.out.println(\"Error we will switch your input\");
sum = sum + a;
}
System.out.println(\"Your sum is: \"+sum); }
}
}
