黑马程序员技术交流社区
标题:
猜数字游戏
[打印本页]
作者:
Frankle
时间:
2016-7-26 12:11
标题:
猜数字游戏
自己写了一个猜数字的游戏,结构有点乱,不过还是可以玩的
package com.thread;
import java.util.Random;
import java.util.Scanner;
public class GuessNumber implements Runnable{
private static Scanner scanner;
private static Random random = new Random();
private static int systemNumber = random.nextInt(100);
private static int count = 10;
public GuessNumber(){
System.out.println("游戏开始!");
System.out.println("请输入你的数字(0~99之间的整数),你有10次机会:");
}
public static void restart(){
System.out.println("游戏结束!按回车键重新开始!");
count = 10;
scanner = new Scanner(System.in);
if(scanner.hasNextLine()){
Thread thread2 = new Thread(new GuessNumber());
thread2.start();
}
}
public static void main(String[] args) {
Thread thread = new Thread(new GuessNumber());
thread.start();
}
@Override
public void run() {
while(true){
if(count < 1){
System.out.println("机会已经用完!你真笨!");
restart();
}
try{
scanner = new Scanner(System.in);
int num = scanner.nextInt();
if(num < 100 && num > 0){
if(num == systemNumber){
System.out.println("恭喜你,猜对了!");
restart();
}else if(num > systemNumber){
count --;
System.out.println("数字大了!再猜一下!剩余机会"+count+"次");
}else{
count --;
System.out.println("数字小了!再猜一下!剩余机会"+count+"次");
}
}else{
System.out.println("数字超出范围!请重新输入!");
}
}catch (Exception e) {
System.out.println("请输入数字!");
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2