对Java一窍不通的我是霸王硬上弓硬生生无脑敲出个猜数字游戏为了对付一下不得不交的期末作业Orz
(估计多半还是不愿承认上次亚洲区域赛那道大数题我没搞出来(/难过))
期间手残不小心点了删除,还好Eclipse还能恢复一段时间内的部分文件,有惊无险。。在这里备份下
Guess.java
package guessnum;
import java.util.*;
public class Guess {
public int produce() {
int a = (int)(Math.random()*(9999-1000+1))+1000;//产生1000-9999的随机数
return a;
}
public void check(int gssnum,int sysnum) {
int g[] = new int[4];
int s[] = new int[4];
int book[] = new int[4];
char answer[] = new char[4];
g[0]=gssnum/1000;
g[1]=gssnum/100%10;
g[2]=gssnum/10%10;
g[3]=gssnum%10;
s[0]=sysnum/1000;
s[1]=sysnum/100%10;
s[2]=sysnum/10%10;
s[3]=sysnum%10;
int flag=0;
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
if(i==j&&g[i]==s[j]) {
book[i]=1;
flag=1;
}
}
}
if(flag==0) {
System.out.println("怎么回事小老弟?你哪一位都没猜对!");
System.out.println("当前已知答案为:\n****");
} else {
System.out.print("第");
int format=0;
for(int i=0;i<4;i++) {
if(book[i]==1) {
answer[i] = (char)(s[i]+48);
if(format==1) System.out.print(",");
System.out.print(i+1);
format=1;
} else {
answer[i] = '*';
}
}
System.out.println(" 位猜对了");
System.out.println("当前已知答案为:");
for(int i=0;i<4;i++) {
System.out.print(answer[i]);
}
System.out.println();
}
}
}
Start.java
package guessnum;
import java.util.Scanner;
public class Start {
public static void main(String[] args) {
Guess g = new Guess();
int sysnum = g.produce();
System.out.println("系统已生成一个四位数!");
System.out.println(sysnum);
System.out.println("请输入您猜的四位数:");
Scanner input = new Scanner(System.in);
int cnt=0;
while(true) {
cnt++;
String s = input.nextLine();
try {
int gssnum = Integer.parseInt(s);
g.check(gssnum, sysnum);
if(cnt%3==0) {
System.out.println("您已猜了"+cnt+"次,是否继续?(继续输入1否则输入0查看答案输入3)");
while(true) {
s = input.nextLine();
int flag = Integer.parseInt(s);
if(flag==1) {
break;
}
else if(flag==0) {
System.exit(0);
}
else if(flag==3) {
System.out.println(sysnum);
break;
}
}
}
if(gssnum==sysnum) {
System.out.println("恭喜你猜对了!再来一局吗?(继续输入1否则输入0)");
while(true) {
System.out.println("请输入数字1或0:");
s = input.nextLine();
int flag = Integer.parseInt(s);
if(flag==1) {
sysnum = g.produce();
System.out.println("系统已生成一个四位数!");
System.out.println(sysnum);
System.out.println("请输入您猜的四位数:");
cnt=0;
break;
} else if(flag==0){
System.exit(0);
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("输入有误,请输入数字!");
}
}
}
}
(就这样的无脑代码我竟硬生生搞了两个多小时,我太菜了,如果不小心被谁看到请不要嘲笑Orz)