黑马程序员技术交流社区
标题:
关于一道编程题的思考过程(密码错误五次跳出)
[打印本页]
作者:
vanish
时间:
2015-8-3 17:22
标题:
关于一道编程题的思考过程(密码错误五次跳出)
楼主初学者,这道题是在基础班上课老师给出的,题目大概是:有一个游戏,登陆游戏需要输入正确密码,如输入错误则继续反复输入,输入错误次数超过五次,则跳出程序,密码正确则进入游戏。由于升基础班入学考试要求手写代码,于是这道题老师让演练下。写的时候就发现,我已经变成不用电脑写不出代码,一下是第一版(手写板):
class Key
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("请输入密码key:");
int key = sc.nextInt;
if(key==12345)
System.out.println("进入");
else
while (key!=12345)
{
System.out.println("输入错误重新输入:");
int x = 0;
x++;
if(x>5)
exit(0);
}
}
}
复制代码
不难看出手写板错漏百出,思路混乱,循环处理的不咋地,就连Scanner包都忘导了,几经思考,重新缕清思路,出现了第二版:
import java.util.Scanner;
class Key{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
while(true){
System.out.println("请重新输入:");
int passWord=sc.nextInt();
if(passWord==12345)){ //字符串用equals(),int 用 ==
System.out.println("进入");
break;
}
else{
System.out.println("错误");
count++;
}
if(count==5)
{
System.exit(0);
}
}
}
复制代码
第二版看似没有什么问题,运行结果什么的也都符合要求,起先觉得就这样很完善了,直到一次偶然的测试发现输入012345也能成功进入,不能保证密码的唯一性,且文字反馈也做得不够好,于是出现了第三版:
import java.util.Scanner;
class Key{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
while(true){
System.out.println("请重新输入:");
int passWord=sc.nextInt();
if(passWord==12345)){ //字符串用equals(),int 用 ==
System.out.println("进入");
break;
}
else{
System.out.println("错误");
count++;
}
if(count==5)
{
System.exit(0);
}
}
}
复制代码
这也是最终版本,还请各位大神指教!
作者:
vanish
时间:
2015-8-3 17:26
给自己顶下!
作者:
vanish
时间:
2015-8-3 18:31
作者:
章浩
时间:
2015-8-3 21:05
.。。。。。。。。。。
作者:
chad8753
时间:
2015-8-3 22:43
,,,,,,,,,,,,,
作者:
Clouddd
时间:
2015-8-3 22:53
记得我刚刚学习Java的时候用了近一年的editplus,没去用过ide,现在自己自学到web这边发现当初自己一行一行敲进去的成果出来了!楼主也加油!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2