Java练习题精选6-10
- 一、第六题
- 二、第七题
- 第八题
- 第九题
- 第十题
一、第六题
如何将两个变量的值进行交换?假设变量a=1,b=2。
public class Main {public static void main(String[] args) {int a = 1;int b = 2;int tmp;System.out.println("交换前a=" + a + "; b=" + b);tmp = a;a = b;b = tmp;System.out.println("交换后a=" + a + "; b=" + b);}
}
二、第七题
用户输入一个年份和月份,输出其对应的天数
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("请输入年份:");int year = sc.nextInt();System.out.print("请输入月份:");int month = sc.nextInt();int days = 0;switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:days = 31;break;case 4:case 6:case 9:case 11:days = 30;break;case 2:int t = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 1 : 0;days = 28 + t;break;}System.out.println(year + " 年 " + month + "月有" + days + "天");}
}
第八题
输出数字1-10:
public class Main {public static void main(String[] args) {for (int n = 1; n <= 10; n++){System.out.println("n = " + n);}}
}
第九题
输出1-100累加和
public class Main {public static void main(String[] args) {int sum = 0;for (int i = 1; i <= 100; i++){sum += i;}System.out.println("1-100的累加和是:" + sum);}
}
第十题
输出1-100的偶数和
public class Main {public static void main(String[] args) {int sum = 0;for (int i = 1; i <= 100; i++){if (i % 2 == 0)sum += i;}System.out.println("1-100的偶数和是:" + sum);}
}