Familiar with the use of the string method to determine whether the file name is legitimate
In addition to learning, write a little exercise to solidify the method of string application.
Task:
1. Determine the type of content that the user chooses to enter
2, if it is a Java file, output "you entered a Java filename"
3, if the email address, the output "you entered the email address"
4. If none, the output "cannot parse what you have entered"
The code is as follows:
1 Public Static voidMain (string[] args) {2Scanner in =NewScanner (system.in);3 BooleanFlag =true;4 Do {5SYSTEM.OUT.PRINTLN ("Please tell me what you want to know:");6String name =In.next ();7 8 Switch(Jude (name)) {9 Case1:TenSYSTEM.OUT.PRINTLN ("You have entered a Java file name"); OneFlag =false; A Break; - Case2: -SYSTEM.OUT.PRINTLN ("You have entered an email address")); theFlag =false; - Break; - Case-1: -SYSTEM.OUT.PRINTLN ("Cannot parse what you entered, please re-enter!") "); + Break; - } +} while(flag); A in.close (); at } - - /* - * Judging Format - */ - Private Static intJude (String Name) { in - intcount1 = 0;//the number of the string that contains the. to intCount2 = 0;//contains the number of @ in the string + - for(inti = 0; I < name.length (); i++) {//Number of statistics the if(Name.charat (i) = = '. ') { *count1++; $ }Panax Notoginseng if(Name.charat (i) = = ' @ ') { -count2++; the } + } A if(Count1 = = 1 && count2 = 1) { the //get the location of the "@" symbol in the mailbox + intIndex2 = Name.indexof (' @ ')); - //get the "." In the mailbox Location of the number $ intIndex3 = Name.indexof ('. ')); $ if(Index2>0 && index3-index2> 1&&index3!=name.length ()-1) {//The judgment must contain the "@" symbol, and "@" must be in the "." Before - - return2; the } - }Wuyi if(Count1 > 0) { the //gets the name of the last occurrence of "." Location of the number - intindex = Name.lastindexof ('. ')); Wu //get the suffix of a file -String prefix =name.substring (index); About $ //The judgment must contain the "." Number, and cannot appear in the first place, with the suffix named "java" - if(Index! =-1 && Index! = 0 && prefix.equals (". Java")) { - - return1; A } + } the return-1; - $}
Operation Result:
This is in accordance with my own understanding of the small program, mainly used to be familiar with the use of the method of the string class, there may be a lot to improve the place, if there are errors in the place please point out thank you!!
Java Basics-Programming exercises (III)