0

Guys i came across this code snippet and i have one question

// Is the passed string a number? public static boolean isNumber(String s) { if (s.length() == 0) { return false; } char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (i != 0 && c == '-') { // the string contains a hyphen return false; } if (!Character.isDigit(c) && c != '-') { // not a number and doesn't start with a hyphen return false; } if (i == 0 && c == '-' && chars.length == 1) { // not a hyphen return false; } } return true; } There are 3 if statements after the first if statement. The method check for a number in a string. Character.isDigit(c) would suffice for that. What is the need for the three if statements. I dont see the need for 3 if statement. Just Character.isDigit() will do the trick. Plis tell me am i wrong ??

10th Jan 2022, 4:35 AM
stephen haokip
stephen haokip - avatar
1 Réponse
+ 1
The number could be negative. In that case, a hyphen ('-') is a valid character in a number which is not a digit (isDigit() would fail). But a hyphen only makes sense under certain conditions. It seems to me, those if's test those conditions.
10th Jan 2022, 6:19 AM
Agnes Ahlberg
Agnes Ahlberg - avatar