Java Programming Practice: Determine whether the Java file name is correct, determine whether the mailbox format is correct, and count the number of times a character in a specified string appears
1. Determine whether the Java file name is correct and whether the mailbox format is correct
Function: determines whether the Java file name is correct and whether the mailbox format is correct. Valid file names should end with. java; valid mailbox names
At least "@" must be included, and "@" must be earlier.
Exercise code:
Public class Test {public static void main (String [] args) {// Java file name String fileName = "HelloWorld. jav "; // email String email =" [email protected] "; // judge. whether the java file name is correct: the valid file name should be. java end/* Reference step: 1. Get the last appearance in the file name ". "Location 2, according ". "Location, get the file suffix 3, Judge ". "Location and file suffix * // obtain the last appearance in the file name ". "No. int index = fileName. lastIndexOf (". "); // get the file suffix String prefix = fileName. substring (index); // determines that it must contain ". ", and cannot appear in the first place, with the suffix" java "if (Index> 0 & prefix. equals (". java ") {System. out. println ("the Java file name is correct");} else {System. out. println ("invalid Java file name");} // determines whether the mailbox format is correct: a valid mailbox name must contain at least "@" and "@" is ". "previous/* Reference steps: 1. Get the" @ "symbol location in the file name. 2. Get the email address ". "Location 3. The judgment must contain the" @ "symbol, and" @ "must be ". "Before * // get the" @ "symbol in the mailbox, int index2 = email. indexOf ("@"); // get email ". "int index3 = email. indexOf ('. '); // The judgment must contain the "@" symbol, and "@" must be in ". "Before if (index2! =-1 & index3> index2) {System. out. println ("correct email format");} else {System. out. println ("invalid email format ");}}}
Running result:
Count the number of times the character 'a' appears in a specified string
Function: counts the number of times the character 'a' appears in a specified string.
Analysis: You can traverse each character in the string cyclically to determine whether it is character a. If yes, the number of occurrences is accumulated.
Exercise code:
Public class Test {public static void main (String [] args) {// defines a String s = "aljlkdsflkjsadjfklhasdkjlflkajdflwoiudsafhaasdasd"; // number of occurrences int num = 0; // cyclically traverse each character to determine whether it is character a. If yes, the accumulated times for (int I = 0; I <s. length (); I ++) a = "" if = "" pre = ""> <p> </p> <p> running result: </p> </p>