Algorithm
-
Input: Accept a string as input.
-
Initialize Variables:
- Initialize a boolean variable, let's call it
isNumeric
, totrue
.
- Initialize a boolean variable, let's call it
-
Iterate Through Characters:
- Use a loop to iterate through each character in the input string.
-
Check Each Character:
- For each character, check if it is a numeric digit.
- You can use the
Character.isDigit(char)
method to check if a character is a digit. - If a character is not a digit, set
isNumeric
tofalse
and break out of the loop.
- You can use the
- For each character, check if it is a numeric digit.
-
Output:
- After the loop, if
isNumeric
is stilltrue
, then the entire string is numeric.
- After the loop, if
-
Print/Return Result:
- Print or return the result based on the value of
isNumeric
.
- Print or return the result based on the value of
Code Examples
#1 Code Example- Java Programing Check if a string is numeric
Code -
Java Programming
public class Numeric {
public static void main(String[] args) {
String string = "12345.15";
boolean numeric = true;
try {
Double num = Double.parseDouble(string);
} catch (NumberFormatException e) {
numeric = false;
}
if(numeric)
System.out.println(string + " is a number");
else
System.out.println(string + " is not a number");
}
}
Copy The Code &
Try With Live Editor
Output
12345.15 is a number
#2 Code Example- Check if a string is numeric or not using regular expressions (regex)
Code -
Java Programming
public class Numeric {
public static void main(String[] args) {
String string = "-1234.15";
boolean numeric = true;
numeric = string.matches("-?\\d+(\\.\\d+)?");
if(numeric)
System.out.println(string + " is a number");
else
System.out.println(string + " is not a number");
}
}
Copy The Code &
Try With Live Editor
Output
-1234.15 is a number
Demonstration
Java Programing Example to Check if a String is Numeric-DevsEnv