【刷题学习Java】——分支的注意事项
🎉个人主页: ✨往期专栏: 🎖️系列专栏: 🔥推荐一款模拟面试,刷题神器👉
❤️欢迎各位小伙伴们!强烈推荐一款刷题神器👉 🔥这是一款专注于程序员的学习和成长的专业平台,有许多专业的IT面试题库,精选了多家知名企业的面试题,全方位提升你的IT技能,轻松面对各大企业面试。
题目
计算商品折扣
import java.util.*; public class Main { public static void main(String[] args) { Scanner console = new Scanner(System.in); int price = console.nextInt(); int cost = 0; //write your code here...... if (price < 100) { cost = price; }else if (price < 500) { cost = (int)(price * 0.9); } else if (price < 2000) { cost = (int)(price * 0.8); } else if (price < 5000) { cost = (int)(price * 0.7); } else { cost = (int)(price * 0.6); } System.out.println(cost); } }
判断体重指数
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double height = scanner.nextDouble(); double weight = scanner.nextDouble(); double ibm=weight/(height*height); String i=ibm<18.5?"偏瘦":ibm<20.9?"苗条" :ibm<24.9?"适中":"偏胖"; //write your code here...... System.out.println(i); } }
判断学生成绩等级
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String grade =scanner.next(); //write your code here...... switch(grade){ case "A": System.out.println("优秀"); break; case "B": System.out.println("良好"); break; case "C": System.out.println("及格"); break; case "D": System.out.println("不及格"); break; default: System.out.println("未知等级"); } } }
邮箱验证
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.next(); String emailMatcher="[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+"; //write your code here...... if(str.matches(emailMatcher)) System.out.println("邮箱格式合法"); else System.out.println("邮箱格式不合法"); } }
switch注意事项
- 表达式数据类型,应该和case后的常量类型一致,或者是可以自动转换成相互比较的类型,比如输入的是字符,而常量是int。
- switch(表达式)中的表达式的返回值必须是:(byte,short,int,char,enum,String)
- case子句中的值必须是常量,而不能是变量。
- default子句是可选的,当没有匹配的子句时,执行default。
- break语句用来执行完一个case分支后使程序跳出switch语句,如果没有break,程序会顺序执行到switch结尾 ,除非遇到break。
switch和if的比较
- 如果判断的具体数值不多,而且符合byte,short,int,char,enum,String这6钟类型,建议用switch。
- 其他情况:对区间判断,对结果为Boolean类型判断,使用if,if的使用范围更广。
结尾
Java的学习必须是有条理、有逻辑的由浅入深。学习Java,一定要理论+实践,对于刚入门的小白来说,练习是必不可少的,想要继续提升能力,都可以去牛客刷题练习。而且可以看到别人的解题思路和解题方法,对自己有非常棒的提升赶紧学习起来吧!❤️
下一篇:
JAVA入门——Day06(分支语句)