Scanner
next()
- 遇到空格等空白符,就认为输入结束
nextLine()
- 遇到回车换行,就认为输入结束
案例1:求闰年
-
能被4整除,不能被100整除
-
能被400整除
public class Test { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("请输入年份:"); int year = input.nextInt(); int days = 28; if(year%4==0 && year%100!=0 || year%400==0){ days++; } System.out.println(year + "年的2月份共" + days + "天"); input.close(); } }
案例2:求最大值
class Day03_Test08_MaxValueExer{
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("请输入第1个整数:");
int a = input.nextInt();
System.out.print("请输入第2个整数:");
int b = input.nextInt();
System.out.print("请输入第3个整数:");
int c = input.nextInt();
int max = a>b ? a : b;
max = max>c ? max : c;
System.out.println(a+","+b+","+c+"中最大的是:"+ max);
}
}
案例3:判断学生成绩等级
public static void main(String[] args) {
int score = 89;
if(score<0 || score>100){
System.out.println("你的成绩是错误的");
}else if(score>=90){
System.out.println("你的成绩属于优秀");
}else if(score>=80){
System.out.println("你的成绩属于好");
}else if(score>=70){
System.out.println("你的成绩属于良");
}else if(score>=60){
System.out.println("你的成绩属于及格");
}else {
System.out.println("你的成绩属于不及格");
}
}
案例4:输入年份,月份,求该月总天数
public static void main(String[] args){
//从键盘输入一个年份,和月份
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("年份:");
int year = input.nextInt();
System.out.print("月份:");
int month = input.nextInt();
if(year>0){
if(month>=1 && month<=12){
//合法的情况
int days;
if(month==2){
if(year%4==0 && year%100!=0 || year%400==0){
days = 29;
}else{
days = 28;
}
}else if(month==4 || month==6 || month==9 || month==11){
days = 30;
}else{
days = 31;
}
System.out.println(year+"年" + month + "月有" + days +"天");
}else{
System.out.println("月份输入不合法");
}
}else{
System.out.println("年份输入不合法");
}
}
案例5:根据指定月份输出对应季节
public class SwitchTest02 {
public static void main(String[] args) {
//指定一个月份
int month = 5;
switch(month) {
case 1:
case 2:
case 12:
System.out.println("冬季");
break;
case 3:
case 4:
case 5:
System.out.println("春季");
break;
case 6:
case 7:
case 8:
System.out.println("夏季");
break;
case 9:
case 10:
case 11:
System.out.println("秋季");
break;
default:
System.out.println("你输入的月份有误");
break;
}
}
}