JAVA零基础猜数小游戏和整数分解
- 猜数小游戏
- 相当于让计算机出一个随机数,然后让用户来猜用户每次输入一个数,就跟他说猜的数大了还是小了知道用户猜中位置,最终还要告诉他一共猜了几次数字
- 因为需要不段让用户去猜这个数字所以这个小游戏肯定用到了循环
核心的重点还是循环
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = (int)(Math.random()*50+1); int b; int count=0; do { b= sc.nextInt(); count=count+1; if (b>a){ System.out.println("大"); }else if(b<a){ System.out.println("小"); } }while (b!=a); System.out.println("恭喜你猜对了,你猜了"+count+"次"); } }
编写while true循环
提示用户输入,用用户输入的数字和系统生成的数字比较
如果比系统的数字大提示猜大了
如果比系统的数字小提示猜小了
如果等于即猜对了然后跳出循环
- 整数的分解
- 一个整数是由1至多位数字组成的,如何分解出整数的各个位上的数字,然后加以计算
- 对一个整数做%10的操作,就得到它的个位数
- 对一个整数做/0的操作,就去掉了它的个位数
- 然后再对2的结果做%10,就得到原来数的十位数了
- 依此类推。
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int number; number= sc.nextInt(); int result=0; do { int digit = number%10; result=result*10+digit; System.out.print(digit); number =number /10; }while (number>0); System.out.println(); System.out.print(result); } }