JAVA_if选择结构

3.1.1 if 单选则结构

  1. if(){ ;}
  2. 随机数产生:Math.random() 产生【0,1)的随机数。
    例如:产生【0,6)之间的随机数:6*Math.random()
/**
 * 测试if单选择语句
 * 
 * 学习随机数的建立
 * 
 * @author 王立生
 *
 */
public class testif {
	public static void main(String[] args){
		
		/*产生随机数*/
		double a;
		System.out.println("a="+Math.random());//产生【0,1)的随机数
		
		//产生0到1之间的整数
		
		int b=(int)(6*Math.random()+1);
		System.out.println("b="+b);
		
		int c=(int)(6*Math.random()+1);
		System.out.println("c="+c);
		
		int d=(int)(6*Math.random()+1);
		System.out.println("d="+d);
		
		int count=b+c+d;
		
		if(b+c+d>=15){
			
			System.out.println("您手气超好!");}
		
			else if(b+c+d>=10&&b+c+d<15){
				System.out.println("您手气还不错。");}
		
			else{
				System.out.println("您手气不太行。。。");}
					
	}

}

3.1.2 if -else 双选择结构

  1. if(){ ;}
    else{;}

  2. 数学表达:
    pi: Math.PI
    求r平方:Math.pow(r,2)

代码示例:

/**
 * 测试if  else结构
 * @author 王立生
 *
 */
public class testIfElse {
	public static void main(String[] args){
		
		//产生一个随机数作为半径,计算圆周长和面积
		
		double r=6*Math.random();
		System.out.println("r="+r);
		
		if(r>=3){
			System.out.println("圆的面积为:"+Math.PI * Math.pow(r, 2));}
		
		else{
			System.out.println("圆的周长为:"+2*Math.PI * r);
			
		}
	}

}

3.1.3 if else if else 多选择结构

  1. if(){;}
    else if(){;}
    else if(){;}

    else{;}

代码示例:

/**
 * 测试If else If else多选择结构
 * @author 王立生
 *
 */
public class testIfElseIfelse {
	public static void main(String[] args){
		
		int time=(int)(19*Math.random());
		System.out.println("time="+time);
		
		if(time<=6){
			System.out.println("小学游戏");
		}
		else if(time>6&&time<=9){
			System.out.println("初中玩");
			}
		else if(time>9&&time<=12){
			System.out.println("高中学");
		}
		else if(time>12&&time<=16){
			System.out.println("东华了");
		}
		else{
			System.out.println("北航做准备");
			
		}
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值