搜索
写经验 领红包
 > 生活

今年生肖年份对照表(今年的生肖是怎么排的)

导语:分支判断今年生肖详解

第一种:switch……case

public static void main(String[] args) {Scanner sc=new Scanner(System.in);//控制台输入System.out.println();//提示int year=sc.nextInt()%12;//输入的年份与12求余后得到的余数switch(year) {case 0:System.out.println();break;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;case 6:System.out.println();break;case 7:System.out.println();break;case 8:System.out.println();break;case 9:System.out.println();break;case 10:System.out.println();break;case 11:System.out.println();break;default:System.out.println();}}

①首先创建一个main方法;

②调用Scanner类用于控制台输入年份;

③写一个输出语句用来提示用户输入;

④把输入的年份与12进行求余;(因为一个生肖的轮回为12年)

⑤然后使用switch…… case语句进行判断,case 0是猴年、case 1是鸡年、以此类推。(因为根据历史可知公元1年为鸡年,由此可推出公元1年的前一年为猴年)

小知识:公元1年也称为公元元年恰好是西汉最后一位皇帝汉平帝元始元年.这一年是辛酉年,即鸡年。

!!!重点:每一个case语句结尾都要加上break函数,不然代码会向下穿透,不仅仅输出的结果是求出来的年份,还会把此年份后面的年份一并输出。

⑥在判断最后加上default,用来判断非正常输入的情况。(default在switch……case是用来判断当switch语句里面的所有语句都不成立时执行的语句)

输出结果

第二种:if……else……else if……else

package com.gec.practice;import java.util.Scanner;public class Two {public static void main(String[] args) {Scanner sc=new Scanner(System.in);System.out.println();int years=sc.nextInt();if(years<=0) {System.out.println();}else if(years%12==0) {System.out.println();}else if(years%12==1) {System.out.println();}else if(years%12==2) {System.out.println();}else if(years%12==3) {System.out.println();}else if(years%12==4) {System.out.println();}else if(years%12==5) {System.out.println();}else if(years%12==6) {System.out.println();}else if(years%12==7) {System.out.println();}else if(years%12==8) {System.out.println();}else if(years%12==9) {System.out.println();}else if(years%12==10) {System.out.println();}else if(years%12==11) {System.out.println();}}}

①首先创建一个main方法;

②调用Scanner类用于控制台输入年份;

③写一个输出语句用来提示用户输入;

④先判断输入的年份是否合法,如果不合法则跳出,合法则继续判断。

⑤把输入的年份与12进行求余;(因为一个生肖的轮回为12年)

⑥如果求得的余数是1,则判定今年是鸡年;由此可推出如果求得的余数是0,则判定今年是猴年如果求得的余数是2,则判定今年是狗年……以此类推

欢迎大家评论互动呀~_~

免责声明:本站部份内容由优秀作者和原创用户编辑投稿,本站仅提供存储服务,不拥有所有权,不承担法律责任。若涉嫌侵权/违法的,请反馈,一经查实立刻删除内容。本文内容由快快网络小茹创作整理编辑!