Please write the code in JAVA! Write a static method called getTwoFloats(), whic
ID: 3813157 • Letter: P
Question
Please write the code in JAVA!
Write a static method called getTwoFloats(), which returns an array of two floats based on the problem 5.2 (Homework #5). You can re-use the code you wrote from HW#5.2 or from the model answer provided. Modify the main method to call getTwoFloats and print the two floats in the main method. Example user interface: Welcome to bonus get two floats program Enter two floats separated by a space: a; f asfas fasf a You have entered an invalid input. Enter two floats separated by a space: 5.6 a; fa sf asf as You have entered an invalid input. Enter two floats separated by a space: 12.45 34.56 You entered 12.45 and 34.56 successfully! Press enter key to continue...Explanation / Answer
Hi,
Please find below the Java code-
import java.util.Scanner;
public class HelloWorld{
private static boolean isFloat (String num1,String num2){
boolean isValid = true;
try {
Float.parseFloat(num1) ;
Float.parseFloat(num2) ;
}
catch(NumberFormatException e){
isValid = false;
}
return isValid;
}
public static void main(String []args){
Scanner in = new Scanner(System.in);
System.out.println("Enter two float numbers separated with space");
String numbers = in.nextLine();
String[] parts = numbers.split(" ");
boolean val=isFloat(parts[0],parts[1]);
System.out.println(val);
if(val==true) {
float element1 = Float.parseFloat(parts[0]);
float element2 = Float.parseFloat(parts[1]);
System.out.printf("You entered %f and %f successfully",element1,element2);
}
else
System.out.println("You have entered an invalid Input");
}
}