项目实战——校验文件名和邮箱地址
1.项目实例
假设,在作业提交系统中学生需要录入提交的 Java 文件名称及要提交到的邮箱地址,那么就需要对学生输入的这些信息进行校验,判断输入是否有误。校验的规则为:录入的文件名称必须以“.java”结尾,录入的邮箱地址中必须包含有“@”符号和“.”符号,且“@”在“.”之前。
2.项目实现
在这里使用 String 类中的 indexOf() 方法、charAt() 方法和 lastIndexOf() 方法来完成此程序。具体实现代码如下:
2.1 检查文件名是否合法
if(flag != -1 &&name.charAt(flag+1)=='j'&&name.charAt(flag+2)=='a'
&&name.charAt(flag+3)=='v'&&name.charAt(flag+4)=='a'){
filecon = true;}
else{
System.out.println("The file name is not valid.");}
2.1 检查邮箱名是否合法
if(email.indexOf('@')!=1&&email.indexOf('.')>email.indexOf('@')){
emailcon = true;}
else{
System.out.println("The email name is not valid.");}
2.3 输出验证情况
if(filecon && emailcon){
System.out.println("The job submission was successful.");}
else{
System.out.println("Job submission failed.");}
3. 项目实例
验证成功:
******** Welcome to the job submission system ********
Please enter the name of the JAVA file you want to submit:
ads.java
Please enter the email address to submit to:
ads@qq.com
The job submission was successful.
验证失败:
******** Welcome to the job submission system ********
Please enter the name of the JAVA file you want to submit:
asd.java
Please enter the email address to submit to:
asd@qq.com
The email name is not valid.
Job submission failed.