Please write the code in JAVA! Write a program that will give the user prompt to
ID: 3813155 • Letter: P
Question
Please write the code in JAVA!
Write a program that will give the user prompt to enter two float (or double) values. If the values inputted are correct then display the inputted two values. If user enters characters instead of numbers or if they enter invalid numbers then the program will display the error message and ask the user to re-enter the correct values again. It only exits when the correct input is received and displayed. Example user interface: Welcome to get two floats program Enter two floats separated by a space: a f asf asf a You have entered an invalid input. Enter two floats separated by a space: 212.5 55.5 You entered two valid floats: 212.5 and 55.5 Thank you for giving two floatsExplanation / Answer
HI, Please find my implementation.
Please let me know in case of any issue.
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float f1 = 0;
float f2 = 0;
while(true){
try{
System.out.print("Enter two floats separated by space: ");
f1 = sc.nextFloat();
f2 = sc.nextFloat();
break;
}catch(Exception e){
System.out.println("You have entered an invalid input. Try again.");
// skipping invalid inout line
sc.nextLine();
}
}
System.out.println("You entered two valid floats: "+f1+" and "+f2);
}
}
/*
Sample run:
Enter two floats separated by space: asd e qw
You have entered an invalid input. Try again.
Enter two floats separated by space: 45 34
You entered two valid floats: 45.0 and 34.0
Enter two floats separated by space: 34.43 ed
You have entered an invalid input. Try again.
Enter two floats separated by space: 12.43 56
You entered two valid floats: 12.43 and 56.0
*/