涉及三个知识点:
1.最有效率的代码写出2乘8;
2.用两种方法交换两个变量;
3.根据输入月份输出这个月的天数(用到if和switch);
- /**
- 1.最有效率的代码写出2乘8;
- 2.用两种方法交换两个变量;
- 3.根据输入月份输出这个月的天数(用到if和switch);
- */
- import java.util.Scanner;
- public class Day03Practice
- {
- public static void main(String[] args){
- //最有效率的代码写出2乘8
- int x = 2 , y;
- y = 2 << 3;
- System.out.println("2乘以8 = "+y);
- int a = 6 , b = 9;
- System.out.println("a = 6 , b = 9:交换位置结果是");
- //用第三方变量交换a,b位置
- int temp = a;
- a = b;
- b = temp;
- System.out.println("a = "+a+"b = "+b);
- //不用第三方变量交换a,b位置
- int a1 = 6 , b1 = 9 ;
- a1 = a1^b1;
- b1 = a1^b1;
- a1 = a1^b1;
- System.out.println("a = "+a+"b = "+b);
- /*
- 用switch语句根据输入月份打印出这月的天数
- 思路:
- 每年1,3,5,7,8,10,12月份是31天;
- 4,6月份是28天;9,11月份是29天;2月份不固定
- */
- Scanner sc = new Scanner(System.in) ;
- System.out.println("请输入您要查询的年份:");
- //接收输入的数据
- int number = sc.nextInt();
- String num ;
- if (number == 2)
- {
- num = "28天或29天,看年份";
- }
- else{
- switch (number)
- {
- case 1:case 3:case 5:case 7:
- case 8:case 10:case 12:
- num = "31天";
- break;
- case 4:case 6:
- num = "28天";
- break;
- case 9:case 11:
- num = "29天";
- break;
- default :
- num = "不存在";
- break;
- }
- }
- System.out.println("这个月的天数是"+num);
- }
- }
复制代码 |
|