Java笔记——第二章(Ⅱ)牛刀小试之身高预测

第二章(Ⅱ)牛刀小试之身高预测

一、任务实施
任务:编写一个程序通过父母的身高来预测子女的身高。
输入:父亲身高、母亲身高、孩子性别

公式:
儿子的成年身高=(父亲身高+母亲身高)x1.08 ÷2
女儿的成年身高=(父亲身高x0.923+母亲身高)÷ 2;

输出:孩子的预测身高

代码实现:

package ch02;


public class KidsHeight {

 public static void main(String[] args) {
float fatherHeight=1.75f;
  float motherHeight=1.66f;
  float boyHeight=(float)((fatherHeight+motherHeight)*1.08/2);
  float girlHeight=(float)((fatherHeight*0.923+motherHeight)/2);
  System.out.println("男孩的预测身高为:"+boyHeight+"米");
  System.out.println("女孩的预测身高为:"+girlHeight+"米");
}
}

输出结果:
在这里插入图片描述

二、代码改进(用键盘输入)
1、使用字符输入流(BufferReader)
read(): 读取单个字符
readLine(): 读取一个字符串

2、利用文本扫描类

整型:nextInt()
单精度:nextFloat()
双精度:nextDouble()
字符串:next()

代码实现:

package 身高预测键盘输入;

import java.util.Scanner;
public class keyboard {
public static void main(String[] args) {
double fatherHeight, motherHeight, kidHeight;
  int kidGender;
  String gender="男孩";
  Scanner input = new Scanner(System.in);
  System.out.println("请输入父亲的身高(米):");
  fatherHeight = input.nextDouble();
  System.out.println("请输入母亲的身高(米):");
  motherHeight = input.nextDouble();
  System.out.println("请输入孩子的性别(0代表男孩,其他的代表女孩),");
  kidGender = (int)input.nextDouble();
  if (kidGender == 0) {
   gender="男孩";
   kidHeight=(fatherHeight+motherHeight)*1.08/2;
  }else {
   gender="女孩";
   kidHeight = (fatherHeight*0.923+motherHeight)/2;
  }
  System.out.println("要预测的是:"+gender+"预测的身高为:"+kidHeight);
  input.close();
         }
  }

输出结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值