[Java] 纯文本查看 复制代码
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class GuessNum {
private int tarNum;
private int lowRndLimit=1;
private int highRndLimit=100;
private int tryTimesLimit;
private int tryTimes=0;
private ArrayList<Integer> list = new ArrayList();
public GuessNum(int tryTimesLimit){
this.initTarNum();
this.tryTimesLimit=tryTimesLimit;
}
//创建随机数
public void initTarNum(){
Random r = new Random();
tarNum = r.nextInt(highRndLimit-lowRndLimit+1)+lowRndLimit;
}
//判断猜测结果
public void guess(int scrNum){
list.add(scrNum);
tryTimes++;
if(scrNum==tarNum){
System.out.println("猜中");
System.exit(0);
}else if(scrNum>tarNum){
System.out.println("猜大了,请重新猜");
}else{
System.out.println("猜小了,请重新猜");
}
}
//判断是否还有猜测机会
public boolean hasChance(){
return tryTimesLimit!=tryTimes;
}
//打印猜测过程
public void printGuessHistory() {
for (Integer integer : list) {
System.out.print(integer+" ");
}
}
public static void main(String[] args) {
GuessNum gn = new GuessNum(6);
int scrNum;
Scanner sc = new Scanner(System.in);
while (gn.hasChance()){
System.out.println("输入猜测数字:");
scrNum = sc.nextInt();
gn.guess(scrNum);
}
gn.printGuessHistory();
}
}
[Java] 纯文本查看 复制代码
package com.itheima;
import java.util.Random;
import java.util.Scanner;
public class Test1 {
/*
* 生成一个1-100的随机数
2:用户键盘录入一个数字 ,与该随机数进行比较
3:如果猜数正确,退出程序
4:如果猜大了,打印"猜大了,请重新猜",用户继续猜
5:如果猜小了,打印"猜小了,请重新猜",用户继续猜
6:一共可以猜6次
7:当用户6次都没猜中时,程序结束 ,将用户所猜过的所有结果打印到控制台
*/
public static void main(String[] args) {
Random ra=new Random();
int num=(ra.nextInt(100)+1);
System.out.println(num);
Scanner sc=new Scanner(System.in);
int count=6;
System.out.println("请输入数字:");
int[] allNum=new int[6];
while(true){
System.out.println("您还有"+count+"次机会");
int x=sc.nextInt();
allNum[(6-count)]=x;
count--;
if(x>num){
System.out.println("猜大了,请重新猜");
}else if(x<num){
System.out.println("猜小了,请重新猜");
}else{
System.out.println("Bingo,Game Over");
break;
}
if(count==0)
break;
}
System.out.print("猜过的数为:");
for(int i=0;i<allNum.length;i++)
System.out.print(allNum+"\t");
}
}