0

I cannot understand the code below. but i keep trying

// 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; } Or Plis give me a string or number that satisfy each of the last 3 if statements. Besides i believe the second last if statement will never be satisfied because c cannot have two values at the same time. Am i correct please help.

10th Jan 2022, 4:28 PM
stephen haokip
stephen haokip - avatar
6 Antworten
+ 3
stephen haokip When c = '-' than .isDigit(c) would return false but it could be a minus so you need to make sure that you only return false when c is a letter or another special character(+, &, ? ...)
10th Jan 2022, 5:06 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Hello stephen haokip if s.length() == 0 means if the string is empy. Should be clear that you return false here. Now you create an char array. if(i != 0 && c == '-') Negative numbers like -4 contains a minus at i = 0. If "-" somewhere else return false e.g. s = "1-2", '-' is at i = 1 if(!Character.isDigit(c) && c!='-') c is not a digit and not a minus -> something else (e.g. a letter) so return false e.g. s = "12&45", s = "hello" But if the first char is '-' don't return false because it could be a negative number. if(i==0 && c == '-' && chars.length() == 1) The first char is a minus but your char array contains only one char -> return false. e.g. s = "-" A negative number would have at least a length of 2 So your code works for positive numbers and negative numbers.
10th Jan 2022, 4:48 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Denise thank you
10th Jan 2022, 4:53 PM
stephen haokip
stephen haokip - avatar
0
Denise but i still have doubt
10th Jan 2022, 4:54 PM
stephen haokip
stephen haokip - avatar
0
stephen haokip Just ask.
10th Jan 2022, 5:00 PM
Denise Roßberg
Denise Roßberg - avatar
0
Denise ...IsDigit part... HoW can c have two values at the same time
10th Jan 2022, 5:02 PM
stephen haokip
stephen haokip - avatar