Package practicego;import java.util.scanner;/* * 3. Enter a string that counts how many digits, how many letters, and how many other characters are contained in the string. */public class cto {public static void main (String[] args) { int englishCount = 0;// English alphabet number int spaceCount = 0;// Number of spaces int numCount = 0;// number int otherCount = 0;// number of other characters scanner sc = new scanner (system.in); System.out.println ("Please enter a line of characters:"); string str = Sc.nextline ();// get console input one line of characters char[] ch = Str.tochararray ();// The string you have taken into aA char array for (int i = 0; i < ch.length; i++) { if (Character.isletter (ch[i)) { // determine if it is a letter englishCount++; } else if (Character.isspacechar (ch[i)) { // determine if it is a space spaceCount++; } else if (Character.isdigit (ch[i)) { // Judging whether it is digital numCount++; } else { // above are not considered to be other characters otherCount++; } } system.out.println ("Number of Letters:" + englishcount); system.out.println ("Number of Numbers:" + numcount); System.out.println ("Number of Spaces:" + spacecount); System.out.println ("Number of other characters:" + othercount); }}
Test:
Please enter a line of characters: [email protected] Number of letters: 9 Number of Numbers: 8 Number of spaces: 0 Number of other characters: 2
Please enter a line of characters: YEQC @@@123456aaa number of letters: 7 Number of digits: 6 Number of spaces: 2 Number of other characters: 3
Note: There are three classes in Java that are responsible for manipulating characters: Character, String, StringBuffer. Where the character class operates on a single character, string is an operation on a sequence of characters, and StringBuffer is an operation on a string of characters.
Statement of the 1.Character
Public final class Character extends Object implements Serializable,comparable<character>
How to construct 2.Character
Public Character (char) {}
3. Common methods
ToString () method
4. Normally, when we use characters, we sometimes need to use the characters of the original data type
char ch = ' a '; char Unichar = ' \u039a '; char[] Chararray = {' A ', ' B ', ' C ', ' d ', ' e '};
The 5.Character class provides some useful classes (that is, static) methods to manipulate characters. You can create a character for a character-constructed object
Character ch1 = new Character (' a ');
Java Loop Exercise: Enter a string that counts how many digits, how many letters, and how many other characters the string contains.