线程
完成任务:在规定时间内,随机打出若干个字母。
分析:
1.首先随机数要进行计时,这里要求的是字母,因此我们要用asc码来操作:
random类随机打出数字。小写字母和数字的关系是字母=(char)数字+65,如a=(char)0+65.
2.计时实现:用线程进行记时,sleep10000ms,即是10s内打出,随后break退出。
代码:
importjava.util.Random;
importjava.util.Scanner;
public classtest {
//计时线程
public static voidtime(){
newThread(newRunnable() {
@Override
public voidrun() {
try{
Thread.sleep(10000);
System.out.println("time over");
//exit
System.exit(-1);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}).start();
}
public static voidmain(String[] args){
//随机生成长度为10的大写字母串,asc码值65-90
Random ran=newRandom();
String str="";
for(inti=0;i<10;i++){
intrandomNum=ran.nextInt(10)+65;
str+=(char)randomNum;
}
System.out.println("please type 10 letter");
System.out.println(str);
Scanner scan =newScanner(System.in);
String result=scan.nextLine();//产生字符串
if(result.equalsIgnoreCase(str)) {
System.out.println("输入正确");
}else{
System.out.println("失败");
}
System.exit(-1);
}
}
输出:
