import java.util.Scanner; public class RicMain { public static void main(String[] args) { String test = "Hello World, it is me"; count(test); //sets x = test? //char[] ch = test.toCharArray()? } public static void count(String x) { char[] ch = x.toCharArray(); //converts x into an array? int letter = 0; int space = 0; int num = 0; for(int i = 0; i < x.length(); i++) //i < test.length()? { if(Character.isLetter(ch[i])) //determines how many letters 'x' has? { letter++ ; //letter + 1 ----> 0+1 } else if(Character.isDigit(ch[i])) //determines how many numbers 'x' has? { num++ ; } else if(Character.isSpaceChar(ch[i])) //determines the spaces 'x' has? { space++ ; } } System.out.println("The string has: "); System.out.println(letter + " letters" + ", " + space + " spaces" + ", " + num + " numbers"); } }
I have another code (I got from online), but I'm trying to understand what's going on on this code (my questions are also inside the code itself). I understand the isLetter(), isDigit(), isSpaceChar(), but how does the for loop determine how many letters, numbers, spaces there are in the String test. Also, in the inner class, the count(test), that is basically setting x equal to test, right?
--- Update ---
The output is:
The string has:
16 letters, 4 spaces, 0 numbers