java用do-while句式猜数字

首先,程序中引用两个工具类

import java.util.Scanner;
import java.util.Random;

之后产生一个[1-100)内的数字,有两种方法

int num = (int)(Math.random()*90 + 10);

或者是使用Random()工具类的方法

1.随机产生一个100以内的整数
Random rand = new Random();
//int num = rand.nextInt();产生的是任意大小的整数
int num = rand.nextInt(100);//产生[0,100)的整数
System.out.println(num);

主体do-while语句

do{
	//循环体至少执行一次
	System.out.println("请输入一个整数: ");
	int guess = scan.nextInt();//为变量赋值

	count++;//输入一次,计数一次
	if (guess > num){
		System.out.println("大了");
	}else if (guess < num){
		System.out.println("小了");
	}else{
		System.out.println("猜对了");
	}
}while(guess != num);

全部代码

import java.util.Scanner;
import java.util.Random;

class Exer1{
	public static void main(String[] args) {
		//产生一个[1-100)的数
		int num = (int)(Math.random()*90 + 10);
		
		/*1.随机产生一个100以内的整数
		Random rand = new Random();
		//int num = rand.nextInt();产生的是任意大小的整数
		int num = rand.nextInt(100);//产生[0,100)的整数
		//System.out.println(num);
		*/
		//2.键盘输入
		Scanner scan = new Scanner(System.in);
		
		//3.声明变量
		int guess;
		int count = 0;

		do{
			//循环体至少执行一次
			System.out.println("请输入一个整数: ");
			int guess = scan.nextInt();//为变量赋值

			count++;//输入一次,计数一次
			if (guess > num){
				System.out.println("大了");
			}else if (guess < num){
				System.out.println("小了");
			}else{
				System.out.println("猜对了");
			}
		}while(guess != num);
		System.out.println("一共猜了:" + count + "次");
	}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值