Check Value is Integer or Not in Java using loop
ADVERTISEMENTS
Check value is integer or not in java using loop. In this article, you will learn how to check value is integer or not in java using while and for loop.
Examples
Input: 20
20 is an integer number.
Input: 21.25
21.25 is a floating-point number.
You should have knowledge of the following topics in java programming to understand these programs:
- Java Strings
- Java
java.util.Scannerpackage - Java
main()method - Java
forloop statement - Java
whileloop statement - Java
if-elsecondition statement - Java
breakkeyword - Java
System.out.println()function
Check Value is Integer or Not in Java using While loop
// Check Value is Integer or Not in Java using While loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String random_number;
int f = 0, i = 0;
System.out.print("Enter the number to check itself: ");
random_number = in.nextLine();
while (random_number.charAt(i) != '\0' && i < (random_number.length() - 1)) {
if (random_number.charAt(i) == '.') {
f = 1;
break;
}
i++;
}
if (f == 1)
System.out.println("\n" + random_number + " is a floating-point number.");
else
System.out.println("\n" + random_number + " is an integer number.");
}
}
Output
Enter the number to check itself: 20
20 is an integer number.
Check Value is Integer or Not in Java using For loop
// Check Value is Integer or Not in Java using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String random_number;
int f = 0;
System.out.print("Enter the number to check itself: ");
random_number = in.nextLine();
for (int i = 0; random_number.charAt(i) != '\0' && i < (random_number.length() - 1); i++) {
if (random_number.charAt(i) == '.') {
f = 1;
break;
}
}
if (f == 1)
System.out.println("\n" + random_number + " is a floating-point number.");
else
System.out.println("\n" + random_number + " is an integer number.");
}
}
Output
Enter the number to check itself: 21.25
21.25 is a floating-point number.
Explanation
In this program, we have taken input 21.25 from the user and parsed this input as a string.
Meanwhile using for loop or while loop on this string we find the . symbol to verify It's an integer or floating-point number.