How do you check if a string contains only digits in Java

Java
x
22
public class CheckStringDigits {
public static void main(String[] args) {
String str = "12345";
boolean isDigit = true;
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
isDigit = false;
break;
}
}
if (isDigit) {
System.out.println("The string contains only digits");
} else {
System.out.println("The string does not contain only digits");
}
}
🤖 Code Explanation
}
The code checks if the string contains only digits. If all the characters in the string are digits, isDigit will be true. Otherwise, isDigit will be false.

More problems solved in Java













