xxxxxxxxxx
public static boolean isInt(String str) {
try {
@SuppressWarnings("unused")
int x = Integer.parseInt(str);
return true; //String is an Integer
} catch (NumberFormatException e) {
return false; //String is not an Integer
}
}
xxxxxxxxxx
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
xxxxxxxxxx
//"% (modulo)" calulates the remainder when the value on the left is divided by the value on the right
float number = 20;
if(number%1 == 0){
println("It is an integer");
} else {
println("It is not an integer");
}
xxxxxxxxxx
string str = "3257fg";
for(int i = 0;i < (strlen(str) - 1);i++) {
if((int)str[i] < 10) {
// it is a number, so do some code
} else {
// it is not a number, do something else
}
}
xxxxxxxxxx
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static void main(String[] args) {
String input = "123.45";
if (isNumeric(input)) {
System.out.println("The string is a number.");
} else {
System.out.println("The string is not a number.");
}
}