28/03/2023 12:49 pm
Topic starter
Notifications
Clear all
How to check if a string contains only digits?
Students’s Forum
1
Posts
2
Users
0
Likes
590
Views
0
How to check if a string contains only digits?
Answer
Add a comment
Add a comment
1 Answer
0
29/03/2023 5:26 pm
class Test { public static void main(String[] args) { String str = "129843875"; boolean containsOnlyDigits = true; for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { // in case that a char is NOT a digit, enter to the if code block containsOnlyDigits = false; break; // break the loop, since we found that this char is not a digit } } if (containsOnlyDigits) { System.out.println("String contains only digits!"); } else { System.out.println("String does not contain only digits!"); } } }
Try the above code.
Add a comment
Add a comment
Forum Information
- 14 Forums
- 1,835 Topics
- 5,051 Posts
- 0 Online
- 1,078 Members
Our newest member: Richardnop
Latest Post: loli
Forum Icons:
Forum contains no unread posts
Forum contains unread posts
Topic Icons:
Not Replied
Replied
Active
Hot
Sticky
Unapproved
Solved
Private
Closed