java 流程控制--猜数字

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

public class GuessNum{
	public static void main(String[] args)
	{
		guess();
	}
	
	public static void guess()
	{
		System.out.println("请输入一个整数");
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();//接收传入的整数
	
		System.out.println("猜数字,范围是0到" + num +",有3次机会");
		Random ran = new Random();
		int ranInt = ran.nextInt(num);//生成一个随机数
	
		int flag = 0;//记录次数
		while(true)
		{
			if(flag < 3)
			{
				System.out.println("请猜第" + (flag+1) +"个数");
				int gusNum = sc.nextInt();
				if(gusNum == ranInt){
					System.out.println("猜对了,数字是" + ranInt);
					break;
				}else if(gusNum < ranInt){
					System.out.println("猜小了");
				}else{
					System.out.println("猜大了");
				}
				flag++;
			}else{
				System.out.println("机会用完啦");
				break;
			}
		}
	}
}

  

posted @ 2018-11-14 14:41  SasaL  Views(209)  Comments(0Edit  收藏  举报