Introduction
In this lab, you will learn how to use the Java intValue()
method of the Float
class to convert a Float
object into an integer value.
In this lab, you will learn how to use the Java intValue()
method of the Float
class to convert a Float
object into an integer value.
touch ~/project/FloatToInt.java
import java.util.Scanner;
public class FloatToInt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Getting the user input as float value
System.out.print("Enter a floating point value: ");
float f = sc.nextFloat();
// Creating a Float object from the user input
Float f1 = f;
// Converting the Float object to int
int i = f1.intValue();
// Displaying the int value
System.out.println("Float value: " + f1);
System.out.println("Int value: " + i);
}
}
CTRL+X
, then Y
, then ENTER
.javac ~/project/FloatToInt.java
java FloatToInt
Enter a floating point value: 45.6
Float value: 45.6
Int value: 45
touch ~/project/FloatToInt.java
import java.util.Scanner;
public class FloatToInt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
// Getting the user input as float value
System.out.print("Enter a floating point value: ");
float f = sc.nextFloat();
// Creating a Float object from the user input
Float f1 = f;
// Converting the Float object to int
int i = f1.intValue();
// Displaying the int value
System.out.println("Float value: " + f1);
System.out.println("Int value: " + i);
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid floating point value.");
}
}
}
CTRL+X
, then Y
, then ENTER
.javac ~/project/FloatToInt.java
java FloatToInt
Enter a floating point value: abcd
Invalid input. Please enter a valid floating point value.
In this lab, you have learned how to use the Java intValue()
method of the Float
class. You have learned how to create a Float
object, convert it to an integer value, and display the output. You have also learned how to handle exceptions when the user enters an invalid input.