Scanner sc = new Scanner(System.in); int month; int age; int hot_price = 60; int cold_price = 40; System.out.println("please enter month"); month = sc.nextInt(); System.out.println("please enter age"); age = sc.nextInt(); if (age >= 0){ if (month >=1 && month <= 12){ if (month >= 4 && month <=10){ if (age >= 18 && age <= 60){ System.out.println("您的票价为:" + hot_price); }else if (age >= 0 && age < 18){ System.out.println("您的票价为:" + hot_price/2); }else if (age > 60 ){ System.out.println("您的票价为:" + hot_price/3); } } else{ if (age >= 18 && age <= 60){ System.out.println("您的票价为:" + cold_price); }else{ System.out.println("您的票价为:" + cold_price/2); } } } else{ System.out.println("月份有误"); } }else{ System.out.println("请输入正确的年龄"); }
Scanner sc = new Scanner(System.in); char c = sc.next().charAt(0); switch (c){ case '1' : System.out.println(1); break; case '2' : System.out.println(2); break; case '3' : System.out.println(3); break; default: System.out.println(666);
}
//判断学生成绩是否及格 System.out.println("请输入成绩:"); Scanner sc = new Scanner(System.in); double score = sc.nextDouble(); int c = (int)score/60; switch (c){ case 0 : System.out.println(score + "不及格"); break; case 1 : System.out.println(score + "及格"); break; default: System.out.println("请输入正确的成绩"); }
踩坑:一开始把0和1加上了‘’,导致一直走default,注意case后面常量的值的类型一定要与表达式保持一致!
//根据季节输出对应的月份 System.out.println("请输入月份:"); Scanner sc = new Scanner(System.in); byte month = sc.nextByte(); switch (month){ case 1 : case 2 : System.out.println("winter"); break; case 3 : case 4 : case 5 : System.out.println("spring"); break; case 6 : case 7 : case 8 : System.out.println("summer"); break; case 9 : case 10 : case 11 : System.out.println("fall"); break; case 12 : System.out.println("winter"); break; default: System.out.println("请输入正确的月份"); }
使用了穿透
int i = 0; for (; i < 10; ) { i++; System.out.println("666"); }
for(; ;){ xxxx}表示一个死循环
3.循环的初始条件可以有多条语句,但要求类型一致且用逗号分隔开。变量迭代语句也可以有多条,也是用逗号隔开。
int max = 3; for(int i = 0, j = 0; i < max ; i ++ , j +=2){ System.out.println("i =" + i + "j = " + j); }
找出范围内x的倍数
Scanner sc = new Scanner(System.in); System.out.println("从:"); int start = sc.nextInt(); System.out.println("到:"); int end = sc.nextInt(); System.out.println("多少的倍数:"); int mod = sc.nextInt(); int sum = 0; int count = 0; for (;start<=end;start++){ if (start % mod ==0){ System.out.println("范围内是"+mod+"的倍数的数有:"+ start); count++; sum+=start; } } System.out.println("共有" + count +"个"); System.out.println("和为" + sum);