此系列文章收录大量Java经典代码题(也可以算是leetcode刷题指南),希望可以与大家一起努力学好Java。3、2、1,请看!
目录
1.根据输入的运算符(+、-、*、/)进行计算
2.随机生成一个整数(1-100),让用户猜数,每次给出大小提示,并记录猜数次数。如下例:
3.输入一个日期(包括年、月、日)计算该日期是该年的第几天
4.输入两个正整数,并利用辗转相除法求出它们的最大公约数。
1.根据输入的运算符(+、-、*、/)进行计算
if分支语句
public static void main(String[] args) throws Exception {//输入运算符System.out.println("请输入运算符");Scanner scn=new Scanner(System.in);char op=scn.next().charAt(0);//输入两个运算数double x=scn.nextDouble();double y=scn.nextDouble();if(op=='+')System.out.println(""+x+op+y+"="+(x+y));else if(op=='-')System.out.println(""+x+op+y+"="+(x-y));else if(op=='*')System.out.println(""+x+op+y+"="+(x*y));else if(op=='/')System.out.println(""+x+op+y+"="+(x/y));else{System.out.println("运算错误");}}
switch分支语句
public static void main(String[] args) throws Exception {//输入运算符System.out.println("请输入运算符");Scanner scn=new Scanner(System.in);char op=scn.next().charAt(0);//输入两个运算数double x=scn.nextDouble();double y=scn.nextDouble();switch (op) {case '+':{System.out.println(""+x+op+y+"="+(x+y));break;}case '-':{System.out.println(""+x+op+y+"="+(x-y));break;}case '*':{System.out.println(""+x+op+y+"="+(x*y));break;}case '/':{System.out.println(""+x+op+y+"="+(x/y));break;}default:{System.out.println("运算错误");break;}}}
2.随机生成一个整数(1-100),让用户猜数,每次给出大小提示,并记录猜数次数。如下例:
while循环语句
public static void main(String[] args) throws Exception {int x=(int)Math.random()*100+1;//Math.random()随机生成[0,1)浮点数System.out.println("请输入你猜的数字");Scanner scn=new Scanner(System.in);int guessn=scn.nextInt();int num=1;//猜数次数while (guessn!=x) {if (guessn>x) {System.out.println("大了");}else if (guessn<x) {System.out.println("小了");}num++;System.out.println("请输入你猜的数字");guessn=scn.nextInt();}System.out.println("猜对了!猜了"+num+"次");}
3.输入一个日期(包括年、月、日)计算该日期是该年的第几天
for循环语句
public static void main(String[] args) throws Exception {//输入年、月、日System.out.println("请输入年、月、日");Scanner scn=new Scanner(System.in);int year=scn.nextInt();int month=scn.nextInt();int day=scn.nextInt();int sum=0;for(int i=1;i<month;i++){if(i==1||i==3||i==5||i==7||i==8||i==10||i==12)//大月:31天sum+=31;else if(i==4||i==6||i==9||i==11)//小月:30天sum+=30;}if(month>2){if(year%4==0&&year%100!=0||year%400==0)//判断闰年sum+=29;else sum+=28;}sum+=day;//单独算本月天数System.out.println("这是今年的第"+sum+"天");}
}
4.输入两个正整数,并利用辗转相除法求出它们的最大公约数。
辗转相除法步骤
- 初始化:选择两个正整数a和b,其中a>b。
- 计算余数:用a除以b,得到商和余数r。
- 迭代:将b设为a,将r设为新的b,然后重复上述步骤,直到余数为0。
- 结果:当余数为0时,最后的非零除数就是a和b的最大公约数。
分析:do-while语句循环体必须要执行一次,为防止输入数字不是整数,使用循环结构控制输入数字,输入两个数至少要被执行一次,因此要用do-while循环语句
public static void main(String[] args) throws Exception {Scanner scn=new Scanner(System.in);int m,n,r;do{System.out.println("请输入两个正整数");m=scn.nextInt();n=scn.nextInt();}while(m<=0||n<=0);r=m%n;//得到余数r。 while (r!=0) {m=n;n=r;r=m%n;}System.out.println("最大公约数是:"+n);//非零除数就是a和b的最大公约数。}
这篇文章到此结束,感谢各位的阅读和所提出的宝贵意见,大家也可以试着自己动手编写代码。如果觉得这篇文章写的还可以或者对您有帮助,麻烦点赞收藏夹转发!!!