一、根据指定月份,打印该月份所属季节,如下图:
用if语句
public class Task1{
public static void main(String[] args){
java.util.Scanner s = new java.util.Scanner(System.in);
System.out.print("请输入一个月份:");
int month = s.nextInt();
String str = "冬";
if(month<1 || month>12){
str = "非法";
}
else if(month>=3 && month<=5){
str = "春";
}
else if(month>=6 && month<=8){
str = "夏";
}
else if(month>=9 && month<=11){
str = "秋";
}
System.out.println(str);
}
}
用switch语句
public class Task2{
public static void main(String[] args){
java.util.Scanner s = new java.util.Scanner(System.in);
System.out.print("请输入一个月份:");
int mon = s.nextInt();
String str="非法";
switch(mon){
case 3: case 4: case 5:
str = "春";
break;
case 6: case 7: case 8:
str = "夏";
break;
case 9: case 10: case 11:
str = "秋";
break;
case 12: case 1: case 2:
str = "冬";
break;
}
System.out.println(str);
}
}
二、从键盘接收一个数字,判断该数字的正负,如下图:
public class Task3{
public static void main(String[] args){
java.util.Scanner s = new java.util.Scanner(System.in);
System.out.print("请输入一个数字:");
double i = s.nextDouble();
System.out.print("您输入的数字是");
if(i<0){
System.out.println("负数");
}
else if(i == 0){
System.out.println("既不是正数也不是负数");
}
else {
System.out.println("正数");
}
}
}
三、从键盘接收一个数字,判断该数字的奇偶性,如下图:
public class Task4{
public static void main(String[] args){
java.util.Scanner s = new java.util.Scanner(System.in);
System.out.print("请输入一个数字:");
int i = s.nextInt();
if(i%2 == 1){
System.out.println("奇数");
}
else{
System.out.println("偶数");
}
}
}