刚刚学了一个产生随机数的函数Random,于是写了一个猜数字的小游戏。下面把我的基础小代码发一下,大家莫笑!
import java.util.Random;
import java.util.Scanner;
class GuessNumber
{
private int guessNumber = 0;
public GuessNumber(){
createNumber();
}
public void createNumber(){
Random random = new Random();
guessNumber = random.nextInt(100);
}
private void guess(){
//long startTime = System.currentTimeMillis();
int counter = 0;
Scanner scanner = new Scanner(System.in);
int number = 0;
while(true){
System.out.print("请输入你要猜的数字:");
number = scanner.nextInt();
counter++;
if(guessNumber == number){
break;
}
if(number > guessNumber){
System.out.println("系统提示:您猜的数字偏大!");
}else {
System.out.println("系统提示:您猜的数字偏小!");
}
}
//long endTime = System.currentTimeMillis();
System.out.println("您总共猜了" + counter +"次。");
//System.out.println("您总共花了" + (endTime - startTime) +"毫秒的时间答对了正确答案!");
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
do{
System.out.print("是否开启新游戏 ? 1.是 2.否 ");
int i = scanner.nextInt();
if(i == 1){
new GuessNumber().guess();
}else{
System.out.print("再见!");
return;
}
}while(true);
}
}