猜字母 猜数字游戏
超类:GuessGanme
派生类:GuessNumberGame
GuessLetterGame
测试类:Test1
超类:GuessGanme
public abstract class GuessGame {
//启动游戏
public void start() {
//产生一个随机数a
String a = suiji();
//提示 猜吧
tishi();
while (true) {
System.out.println("猜吧");
String w = new Scanner(System.in).nextLine();
//比较w和a是否相同 返回结果result
String result = bijiao(w , a);
System.out.println(result);
//判断result是否正确
if (caidui(result)) {
break;
}
}
}
public abstract String suiji() ;
public abstract void tishi() ;
public abstract String bijiao(String w, String a) ;
public abstract boolean caidui(String result);
}
派生类:GuessNumberGame
package day1002_猜游戏;
import java.util.Random;
public class GuessNumberGame extends GuessGame{
@Override
public String suiji() {
//产生一个随机数[1,1000)
int a = 1 + new Random().nextInt(1000);
//int 转换位 String
return String.valueOf(a);
}
@Override
public void tishi() {
System.out.println("数的范围在[1,1000)之间,猜吧!");
}
@Override
public String bijiao(String w, String a) {
int ww = Integer.parseInt(w);
int aa = Integer.parseInt(a);
if(ww>aa) {
return "大了";
}else if(ww<aa){
return "小了";
}else {
return "猜对了!";
}
}
@Override
public boolean caidui(String result) {
return "猜对了!".equals(result);
}
}
派生类:GuessLetterGame
public class GuessLetterGame extends GuessGame{
@Override
public String suiji() {
StringBuilder s = new StringBuilder("QWERTYUIOPADSFGHJKLZXCVBNM");
for (int i = 0; i < 5; i++) {
int b = i + new Random().nextInt(26-i);
char t = s.charAt(i);//访问i的字节
//把i位置设置为b位置
s.setCharAt(i, s.charAt(b));
s.setCharAt(b, t);
}
s.delete(5, 26);
System.out.println(s);
return s.toString();
}
@Override
public void tishi() {
System.out.println("猜字符游戏开始啦!请输入五个不重复的大写字母!");
}
@Override
public String bijiao(String w, String a) {
int q = 0;//相同位置字母相同q++
int e = 0;//字母相同位置不同e++
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//i和j位置字母相同
if (w.charAt(i) == a.charAt(j)) {
if (i == j) {
q++;
} else {
e++;
}
break;
}
}
}
return q+"Q"+e+"E";
}
@Override
public boolean caidui(String result) {
return "CAIDUILE".equals(result);
}
}
测试类:Test1
public class Test1 {
public static void main(String[] args) {
System.out.println("1 猜数字");
System.out.println("2 猜字幕");
System.out.println("请输入你的选择 1 OR 2");
int c = new Scanner(System.in).nextInt();
GuessGame game = null;
switch (c) {
case 1:
System.out.println("你选择的是猜数字游戏!");
game = new GuessNumberGame();
break;
case 2:
System.out.println("你选择的是猜字母游戏!");
game = new GuessLetterGame();
break;
}
game.start();
}
}