Can you explain this 1 line of Java code to me?

Can you explain this 1 line of Java code to me?
This program has you enter a string and it counts up how many were not numbers. I understand it all except the if statement. Can you please explain that? The part compareTo(“0″) < 0 and compareTo("9") > 0 is what is confusing me.
import java.util.Scanner;
public class CountNonDigits {

public static void main(String args[]) {
Scanner input = new Scanner(System.in);

String str;
System.out.println(“Enter a string:”);
str = input.nextLine();

int count = 0;
for(int pos = 0; pos < str.length(); pos++) {
if (str.substring(pos,pos + 1).compareTo("0") < 0 || str.substring(pos,pos + 1).compareTo("9") > 0)
count++;
}

System.out.println(“Count = ” + count);
}
}

Best answer:

The if statement reads like this: if the character that is currently being looked at in the string is < "0" (a text 0) or if it is > “9″ (a text nine), then add one to the count. In otherwords, if the character is a 0-9 character then it does not add one to the count. Remember that with java, the substring takes the index of the character to start at and the character to end at, but does not include the character at the ending position.

Tags: , , , ,

Under Forum

1 Comment for Can you explain this 1 line of Java code to me?

  • 1. JoelKatz  |  June 26th, 2006 at 8:21 pm

    That’s some very strange code, which probably explains why you were having trouble understanding it.

    The ‘compareTo’ function compares two strings as they would be listed in lexicographical order. It returns <0 if the string comes before, 0 if it is the same as, and >0 if it comes after. So this says, roughly: If the character comes before “0″ or after “9″ increment the count. Well, the only characters that don’t come before “0″ or after “9″ are the digits 0 through 9. So this counts the number of non-digits in the string. (Which is probably why it’s called ‘CountNonDigits’.)

    So, again, it goes through each character in the string. If it comes before “0″ lexicographically or after “9″ lexicographically (only the digits do not) then the count is increased.

Leave a Comment for Can you explain this 1 line of Java code to me?

You must be logged in to post a comment.

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories