1、 根据年龄, 来打印出当前年龄的人是少年(低于18), 青年(19-28), 中年(29-55), 老年(56以上)
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请您输入一个年龄(整数):");
int age = scanner.nextInt();
if(age <= 18) {
System.out.println("少年!");
} else if(age <= 28) {
System.out.println("青年!");
} else if(age <= 55) {
System.out.println("中年!");
} else {
System.out.println("老年!");
}
}
}
基本思路:就通过if和else if来判断年龄段,并且输出相对应的年龄阶段。
2、 判定一个数字是否是素数
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请您输入一个整数:");
int num = scanner.nextInt();
boolean flag = true;
for(int i=2;i*i<=num;i++){
if(num % i==0){
flag = false;
}
}
if(flag==false){
System.out.println(num +"不是素数");
}else{
System.out.println(num +"是素数");
}
}
}
基本思路:如果你要判断的数除了能被1和自身整除外还能被别的数整除那么该数一定不是素数。定义一个布尔型的变量方便输出结果。
3、 打印 1 - 100 之间所有的素数
public class test {
public static void main(String[] args) {
int num = 0;
for(int i = 2; i <= 100; i++){
for( num = 2; num < Math.sqrt(i); num++){
if(i % num == 0){
break;
}
}
if(num > Math.sqrt(i)){
System.out.println(i);
}
}
}
}
4、. 输出 1 000 - 2000 之间所有的闰年
public class test{
public static void main(String[] args) {
int year = 0;
for(year = 1000;year <= 2000;year++){
if (year % 100 == 0) {
if (year % 400 == 0) {
System.out.println(year+"是闰年");
}
} else {
if (year % 4 == 0) {
System.out.println(year+"是闰年");
}
}
}
}
}
基本思路:判断闰年要考虑是否是世纪闰年再考虑普通闰年
5、 输出乘法口诀表
public class test{
public static void main(String[] args) {
System.out.println("打印乘法表:");
for(int i = 1;i <= 9;i++){
for(int j = 1;j <= i;j++){
System.out.print(j+"*"+i+"="+i*j+" ");
}
System.out.println("\n");
}
}
}
6、 求两个正整数的最大公约数
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入两个整数:");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int i = num1 % num2;
while(i != 0){
num1 = num2;
num2 = i;
i = num1 % num2;
}
System.out.println("两个数的最大公约数为:" + num2);
}
}
基本思路:辗转相除法:
输入两整数m和n(m>=n)
1)m%n 得出余数,
2)若余数为0,则 n 即为两数的最大公约数
3)若余数不为0,则 m=n,n=余数,再执行第1步。
7、. 计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值。
public class test {
public static void main(String [] args){
double sum = 0;
double tmp = 0;
double flag = 1.0;
for (int i = 1; i <= 100; i++) {
tmp = flag / i;
flag *= -1;
sum += tmp;
}
System.out.println(sum);
}
}