java猜数小程序,学完对数字的操作相关类后可以练习下

import java.lang.Math;
import java.util.Scanner;


public class CaiShu {
private int level;
private int random;
public CaiShu(int level){
//构造函数
this.level = level;
this.random = makeRandom();
}

public int getRandom(){
//获得随机数值,查看随机数
return random;
}

public int makeRandom(){
//产生随机数
switch(level){
case 1:
System.out.println("10以内的随机数:");
return (int)Math.round(Math.random()*10);
case 2:
System.out.println("100以内的随机数:");
return (int)Math.round(Math.random()*100);
case 3:
System.out.println("1000以内的随机数:");
return (int)Math.round(Math.random()*1000);
default:
System.out.println("输入的级别有误");return -1;
}
}

public static boolean allShuZi(String string){
for(char ch : string.toCharArray()){
if(!Character.isDigit(ch))return false;
}
return true;
}

public static void main(String[] args) {
//主函数
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("--------------------------------------");
int level;
boolean notRight=true;//标识是否猜对
System.out.println("按'q'退出程序,按'a'查看正确答案,请输入要挑战的难度:");
System.out.println("1:10以内随机数    2:100以内随机数    3:1000以内随机数");
String firstTemp = sc.nextLine();
if("q".equals(firstTemp)){System.out.println("程序已退出!");System.exit(0);}
else if("a".equals(firstTemp)){System.out.println("在猜数过程中才能查看生成的随机数");continue;}
else if(!CaiShu.allShuZi(firstTemp)){System.out.println("输入的操作数有误,请重新输入");continue;}

level=new Integer(firstTemp);
CaiShu caiShu = new CaiShu(level);
if(caiShu.getRandom()==-1) continue;//如果选择级别出错,进入下一次循环
while(notRight){
System.out.println("输入你的猜想:");
String temp = sc.nextLine();
if("a".equals(temp)){
System.out.println("正确答案是"+caiShu.getRandom());
break;
}
else if(!CaiShu.allShuZi(temp)){
System.out.println("请输入合法的数字");continue;
}
int tempInt = new Integer(temp);
if(tempInt==caiShu.random){
System.out.println("正确,恭喜你");
notRight=false;
}
else{
if(tempInt>caiShu.getRandom()){
System.out.println("你猜的值偏大,重新猜");
}
else{
System.out.println("你猜的值偏小,重新猜");
}
}
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值