Java的输入输出
Java通过Scanner和BufferedReader可以实现对字符串型数据的输入
实现思路:利用正则表达式验证其密码的类型匹配,然后逐个分析字符,进行判断。
本文主要是研究java中BufferedReader和Scanner两种函数的效率
先奉上1081的解答源代码
Scanner实现
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Patest_1081 {
public static void main(String[] args){
Scanner reader=new Scanner(System.in);
int n=reader.nextInt();
String str;
String pwVerify="^([0-9]|[A-Z]|[a-z]|[.]){6,80}";
Pattern pwPattern=Pattern.compile(pwVerify);
reader.nextLine();
for(int i=0;i<n;++i){
str=reader.nextLine();
if(str.length()<6){
System.out.println("Your password is tai duan le.");
continue;
}
Matcher pwMatch=pwPattern.matcher(str);
if(!pwMatch.matches()){
System.out.println("Your password is tai luan le.");
continue;
}
int countNum=0,countChar=0;
for(int k=0;k<str.length();++k){
if(str.charAt(k)>='0'&&str.charAt(k)<='9')countNum++;
if((str.charAt(k)>='a'&&str.charAt(k)<='z')||(str.charAt(k)>='A'&&str.charAt(k)<='Z'))countChar++;
if(countChar>0&&countNum>0){
System.out.println("Your password is wan mei.");
break;
}
}
if(countChar==0)System.out.println("Your password needs zi mu.");
if(countNum==0)System.out.println("Your password needs shu zi.");
}
}
}
PAT中Scanner实现的结果
图片.png
BufferedReader实现
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Patest_1081_2 {
public static void main(String[] args)throws IOException {
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(buf.readLine());
String str;
String pwVerify="^([0-9]|[A-Z]|[a-z]|[.]){6,80}";
Pattern pwPattern=Pattern.compile(pwVerify);
for(int i=0;i<n;++i){
str=buf.readLine();
if(str.length()<6){
System.out.println("Your password is tai duan le.");
continue;
}
Matcher pwMatch=pwPattern.matcher(str);
if(!pwMatch.matches()){
System.out.println("Your password is tai luan le.");
continue;
}
int countNum=0,countChar=0;
for(int k=0;k<str.length();++k){
if(str.charAt(k)>='0'&&str.charAt(k)<='9')countNum++;
if((str.charAt(k)>='a'&&str.charAt(k)<='z')||(str.charAt(k)>='A'&&str.charAt(k)<='Z'))countChar++;
if(countChar>0&&countNum>0){
System.out.println("Your password is wan mei.");
break;
}
}
if(countChar==0)System.out.println("Your password needs zi mu.");
if(countNum==0)System.out.println("Your password needs shu zi.");
}
}
}
PAT中BufferedReader实现的结果
图片.png
然后通过对比我们可以清楚的看到仅仅5组数据,BufferedReader就已经比Scanner展示出了更高的效率。在诸如ACM等等算法的比赛当中,对于运行时间的要求极其苛刻,Java并没有展示出对比C++/C语言的效率。但是,类似PAT给予了Java更宽松的时间规则,因此,Java在一定程度上有比C++/C的一些优势。因此,我们对Java中数据读取的Scanner和BufferedReader进行分析。
但是在多次提交中发现,在PAT中由于计时规则的缘故,导致每次提交的运行时间都各不相同,因此决定利用编译器对于其效率进行一定的测试。因此我决定编写简单的程序对于Java中Scanner和BufferedReader的效率做深度的测试。
首先我们利用Math.random()函数生成10000个随机数当做字符串
public class BufferedReader_vs_Scanner {
public static void main(String[] args)throws IOException {
for(int i=0;i<10000;++i){
System.out.println(Math.random()*1000);
}
}
}
然后将生成的结果放入一个word文档中待用
图片.png
如图中所示,我们已经生成了10000个随机数
然后编写一个简单的读取的BufferedReader和Scanner的程序
图片.png