已解决
【Java】选择语句、循环语句
来自网友在路上 169869提问 提问时间:2023-10-30 04:37:25阅读次数: 69
最佳答案 问答题库698位专家为你答疑解惑
选择语句
if
if 语句的括号内必须是布尔表达式;
else if 语句的括号内也必须是布尔表达式;
public static void main(String[] args) {// 根据年龄输出int age = 0;Scanner scanner = new Scanner(System.in);age = scanner.nextInt();// 括号里面必须是布尔表达式if(age <= 18) {System.out.println("少年");} else if (age >= 19 && age <= 28) {System.out.println("青年");} else if (age >= 29 && age <= 55) {System.out.println("中年");}else {System.out.println("老年");}}
switch
switch 的参数可以是整数、字符串、枚举...
注意:
不能作为switch的参数只有4种:float、double、long、boolean
参数为整型的代码:
public static void main(String[] args) {int day = 0;Scanner scanner = new Scanner(System.in);day = scanner.nextInt();switch (day) {case 1:System.out.println("星期一");break;case 2:System.out.println("星期二");break;case 3:System.out.println("星期三");break;case 4:System.out.println("星期四");break;case 5:System.out.println("星期五");break;default:System.out.println("其他日期");break;}}
参数为String类型的代码:
public static void main(String[] args) {String day;Scanner scanner = new Scanner(System.in);day = scanner.nextLine();switch (day) {case "一":System.out.println("星期一");break;case "二":System.out.println("星期二");break;case "三":System.out.println("星期三");break;case "四":System.out.println("星期四");break;case "五":System.out.println("星期五");break;default:System.out.println("其他日期");break;}}
循环语句
while
while 循环的括号内必须是布尔表达式;
循环中必须要有一个跳出循环的条件,否则就会造成死循环;
判断素数代码:
public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int num = scanner.nextInt();int i = 2;while(i < Math.sqrt(num)) {if(num % i == 0) {System.out.println(num + "不是素数");return ; // return表示方法结束}i++;}System.out.println(num + "是素数");}
for
for(表达式1;布尔表达式;表达式2){循环体};
执行顺序:最后执行表达式2,表达式1只执行一次;
表达式1 -> 布尔表达式(true)-> 循环体 -> 表达式2 ;
布尔表达式(true)-> 循环体 -> 表达式2;
九九乘法表代码:
public static void main(String[] args) {// 九九乘法表for(int i = 1; i <= 9; i++) {for(int j = 1; j <= i; j++) {System.out.print(i + "*" + j + "=" + (i*j) + "\t");}System.out.println();}}
do{}while();
do{}while(); 循环会先执行一次,再进行判断;
while的括号中也只能是布尔表达式;
关键字
break:结束当前循环,不管循环还剩多少次都直接结束;
continue:结束本趟循环,continue本趟循环下的部分都不会执行;
break:当前方法的结束;
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"【Java】选择语句、循环语句":http://eshow365.cn/6-27647-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!