2023/08/16
练习题:生成一个顺序数组,将这个数组的元素打乱顺序后输出
package 练习; import java.util.Arrays; import java.util.Random; public class ShuffleArray { public static void main(String[] args) { int[] a = f(); for(int i=0; i<a.length; i++) { System.out.println(a[i]); } System.out.println("\n\n----------------"); shuffle(a); System.out.println(Arrays.toString(a)); } public static int[] f() { int[] a = new int[5]; for(int i=0; i<a.length; i++) { a[i] = i+1; } return a; } public static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { int j = new Random().nextInt(a.length); int t = a[i]; a[i] = a[j]; a[j] = t; } } }
练习题:接收用户输入的数字,判断在此范围内质数的个数
package cn.cxy.exec; import java.util.Scanner; public class CountPrimeNumber { public static void main(String[] args) { System.out.println("输入整数n,求n内质数的数量"); int n = new Scanner(System.in).nextInt(); count(n); } public static void count(int n) { if(n<2) { System.out.println("没有质数"); return; } if(n==2) { System.out.println("有1个质数"); return; } int count = 1;//已知有一个质数 outer: //从3到n寻找质数 for(int i=3; i<=n ;i++) { double max = 1+ Math.sqrt(i); for(int j=2; j<max; j++) {//在2到<max,找能把i整除的数 if(i%j == 0) { continue outer; } } count++; } System.out.println(n+"内质数的数量:"+count); } }