6个新手Java编程题

打印当前年龄的人是哪个年龄段的

 1 import java.util.Scanner;//scanner的头文件
 2 public class test4 {
 3  
 4  public static void main(String[] args) {
 5 Scanner scan = new Scanner(System.in);
 6   int age = scan.nextInt();
 7   if(age <= 18) {
 8    System.out.println("少年");
 9   }else if (age > 18 && age <= 28){
10    System.out.println("青年");
11   }else if (age > 28 && age <= 55){
12    System.out.println("中年");
13   }else if (age > 55){
14    System.out.println("老年");
15   }
16 
17  }
18 }

判断一个数是否是素数

 1 import java.util.Scanner;//scanner的头文件
 2 public class test4 {
 3  public static void main(String[] args) {
 4 Scanner scan = new Scanner(System.in);
 5   int num = scan.nextInt();
 6   boolean flg = true;
 7   if(num == 0) {
 8    System.out.println("这个数是0");
 9   }
10   if(num == 1) {
11    System.out.println("这个数是1");
12   }
13   for(int i = 2; i < num; i++) {
14    if(num % i == 0) {
15     System.out.println("这个数不是素数");
16     flg = false;
17     break;
18    }
19    if(flg = true) {
20    System.out.println("这个数是素数");
21    break;
22    } 
23   }

 打印1-100间的所有素数

 1 import java.util.Scanner;//scanner的头文件
 2 public class test4 {
 3  public static void main(String[] args) {
 4 int count = 0;
 5   boolean flg = true;
 6   for(int i = 2; i < 100;i++) {
 7    for(int j = 2;j < i; j++) {
 8     if(i % j == 0) {
 9      flg = false;
10      break;
11     }
12     
13    }if (flg) {
14      count++;
15     }else{
16      flg = true;
17     }
18   }System.out.println(count); 
19 
20  
21 }
22 }

 输出1000-2000年中所有的闰年

 1 import java.util.Scanner;//scanner的头文件
 2 public class test4 {
 3  public static void main(String[] args) {
 4 
 5  int count = 0;
 6    for(int year = 1000;year <= 2000;year++) {
 7     if((year%4 == 0 && year%100 != 0) || year % 400 == 0){
 8      count++;
 9      
10     }
11    }
12    System.out.println("1000-2000年中的闰年共有:" +count);
13 }
14 }

输出乘法口诀表

 1 import java.util.Scanner;//scanner的头文件
 2 public class test4 {
 3  public static void main(String[] args) {
 4   Scanner scan = new Scanner(System.in);
 5   int n = scan.nextInt();
 6   for(int i = 1; i <= n; i++) {
 7    for(int j = 1; j <= i; j++) {
 8     int mul = i * j;
 9     System.out.print(j + "*" +i +"="+mul+" ");
10    }
11     System.out.println();
12   }
13  }
14 
15  }

 求两个正数的最大公约数

 1 import java.util.Scanner;//scanner的头文件
 2 public class test4 {
 3  public static void main(String[] args) {
 4   
 5 Scanner scan = new Scanner(System.in);
 6   int n = scan.nextInt();
 7   int m = scan.nextInt();
 8   int max = 1;
 9   int smaller = n < m ? n : m;
10   for(int i = 1; i <= smaller; i++) {
11    if(n % i == 0 && m % i == 0) {
12      max = i;
13    
14    }
15   }System.out.println("最大公约数是:"+max);
16 
17  }
18  }
 
 

猜你喜欢

转载自www.cnblogs.com/Leafbud/p/12756044.html
今日推荐