目录
if/else语句
// 基本语法 if (test) { ststement(s); } else if (test) { statement(s); } else { statement(s); }
根据程序要求选择结构:
- type1:根据用户收入分为高、低和中等收入人群:选择嵌套的if-else if-else语句。
- type2:根据绩点选择优秀和中等优秀的学生:if-elif 结构。
- type3:判断一个数是否可以被2,3,5整除:if-if-if结构。
if-else结构举例:BMI判断
import java.util.*; public class BMI_data { public static void main(String[] args) { System.out.println("This programe is going to calculate your BMI and judge the degree of obesity."); bmi_counting(); } public static void bmi_counting() //根据身高体重计算用户输入的BMI值 { String continue_programe = "yes"; while(continue_programe.equals("yes")) // 当用户输入“yes”时,程序循环进行 { Scanner data = new Scanner(System.in); System.out.print("Please enter your height(Unit: meter)"); double height = data.nextDouble(); System.out.print("Please enter your weight(Unit: kilogram)"); double weight = data.nextDouble(); double bmi = weight/Math.pow(height, 2); System.out.print("Your BMI is "+bmi+".You are "); bmi_judging(bmi); System.out.print("If you want to continue,please enter\"yes\"."); // 注意中间的双引号要用转义字符 continue_programe = data.next(); } if(continue_programe != "yes") { System.out.println("Programe end."); } } public static void bmi_judging(double bmi) // 根据BMI判断用户的肥胖程度 { if (bmi<18.5) { System.out.println("underweight."); } else if (bmi<25) { System.out.println("normal."); } else if (bmi<30) { System.out.println("overweight."); } else { System.out.println("obese."); } } }
测试用例:
累积式算法
举例1:账单累加
// 举例 public static void main(String[] args){ Scanner subtotal = new Scanner(System.in); double subtotal = meals (console); results(subtotal); } public static double meals (Scanner consloe){ System.out.print("How many bills are there?"); int bill = console.nextInt(); double subtotal = 0.0; for (int i = 1;i <= bill;i++){ System.out.print("Bill #" + i + "How much this bill cost?"); double billCost = console.nextDouble(); subtotal = subtotal + billCost; } return subtotal; }
举例2:判断数字的位数
import java.util.Scanner; public class counting_numbers { public static void main(String[] args) { System.out.println("This program is used to receive an integer and then output the number of bits of the integer"); System.out.print("Please enter an integer:"); Scanner in = new Scanner(System.in); int number = in.nextInt(); int count = 0; // do-while 语句(先循环后判断是否满足条件) do { number = number/10; count += 1; System.out.println("step"+count+": numer="+number); }while(number>0); System.out.println("The number of the integer is "+count+"."); } }
运行结果