# All Digits only

• October 28th, 2011, 02:16 PM
kram
All Digits only
In this program allDigits(String): accepts a string and returns true if EVERY character is a digit, otherwise false.

The code seems really simple but i seem not to be getting it here is my code:

//this should produce a false statement because not all characters are digits
public class Test {
public static void main(String[] args) {
String s = "1were";
System.out.print(allDigits(s));
}
public static boolean allDigits(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
if( s.charAt(i) > 0 || s.charAt(i) <= 9) {
return true;
}
}
return false;
}
}

P.S. Im a beginner so let me know if im going in the right direction with this. Thank you[-O<
• October 28th, 2011, 02:23 PM
Actinistia
Re: All Digits only
Just curious but why do you have
Code java:

`int sum = 0;`

in your boolean method? It doesn't seem like you do anything with it. I'm not sure what your specific error is but I'm pretty sure that it might be your if condition. Just think about what the condition is for a moment.
• October 28th, 2011, 02:29 PM
kram
Re: All Digits only
Alright thanks. int sum = 0 was just from another code i forgot to delete it.
• October 28th, 2011, 03:16 PM
d9988
Re: All Digits only
You can use the syntax Character.isDigit to determine if a character is a digit or not. Also, in your code, it's possible to exit with 'True' before checking the whole string (if the first character was a digit, it would return True);

public static boolean allDigits(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) { // if NOT a digit, return false. The ! means "not"
return false;
}
}
return true; // every character was a digit
}
}