Java 练习(六)

  1. 已知高斯随机数的公式为:w=sin(2πv)(21lnu)12w=sin(2\pi v)(-21lnu)^{\frac12},从键盘输入一个(0,1)范围内的u,再输入一个(0,1)范围内的v。计算并输出w的值。
1example:
2
3input:
40.2
50.3
6
7output:
85.529082710300016
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        Scanner scanner = new Scanner(System.in);
 8        double u = scanner.nextDouble();
 9        double v = scanner.nextDouble();
10        scanner.close();
11
12        double w = Math.sin(2 * Math.PI * v) * Math.sqrt(-21.0 * Math.log(u));
13        System.out.println(w);
14    }
15}
  1. 从键盘依次读入两个整数字符,判断一下,他们是否互素。如果互素打印True,不互素打印False。
1example:
2
3input:
49
56
6
7output:
8False
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        Scanner sc = new Scanner(System.in);
 8        int a = sc.nextInt();
 9        int b = sc.nextInt();
10        sc.close();
11
12        System.out.println(gcd(a, b) == 1);
13    }
14
15    public static int gcd(int a, int b) {
16        return b == 0 ? a : gcd(b, a % b);
17    }
18}
  1. 从键盘接收一个整型数据n,并输出一个n*n的图形,其中第i行和第j列如果满足,i可以整除j,或j可以整除i时,输出一个“*”,否则输出一个“ ”(一个空格)。输入输出如图所示:
1example:
2
3input:
43
5
6output:
7***
8** 
9* *
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        Scanner sc = new Scanner(System.in);
 8        int n = sc.nextInt();
 9        sc.close();
10
11        for (int i = 1; i <= n; i++) {
12            for (int j = 1; j <= n; j++) {
13                System.out.print(i % j == 0 || j % i == 0 ? "*" : " ");
14            }
15            System.out.println();
16        }
17    }
18}
  1. 从键盘输入一个n,代表一维数组包含的元素个数。从键盘输入两行由空格分隔的数字字符,代表两个不同的一维数组。如果长度不足n位,用0补足。长度超过n位,只保留n个元素在一维数组中。计算两个向量的欧几里德距离。(即两个向量对应元素差的平方根)
1example:
2
3input:
45
51 2 4 3
62 5 6 9 10 11
7
8output:
912.24744871391589
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.List;
 5
 6public class Main {
 7    public static void main(String[] args) {
 8        Scanner sc = new Scanner(System.in);
 9        int n = sc.nextInt();
10        sc.nextLine();
11        String aVectorString = sc.nextLine();
12        String bVectorString = sc.nextLine();
13        sc.close();
14
15        int[] aVector = parseVector(n, aVectorString);
16        int[] bVector = parseVector(n, bVectorString);
17
18        double tmp = 0.0;
19        for (int i = 0; i < n; i++) {
20            tmp += Math.pow((double) (aVector[i] - bVector[i]), 2);
21        }
22        System.out.println(Math.sqrt(tmp));
23    }
24
25    public static int[] parseVector(int n, String vectorString) {
26        int[] vector = new int[n];
27        String[] stringVector = vectorString.trim().split("\\s+");
28        for (int i = 0; i < n; i++) {
29            vector[i] = stringVector.length > i ? Integer.parseInt(stringVector[i]) : 0;
30        }
31        return vector;
32    }
33}
  1. 从键盘接收一个数字,为当前作业执行需要的秒数,将该秒数整理成xx天xx小时xx分xx秒的形式。
1example:
2
3input:
41000
5
6output:
7Time is:0days,0hours,16minutes and 40 seconds.
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        Scanner sc = new Scanner(System.in);
 8        int second = sc.nextInt();
 9        sc.close();
10
11        int day = second / 86400;
12        second %= 86400;
13        int hour = second / 3600;
14        second %= 3600;
15        int minute = second / 60;
16        second %= 60;
17
18        System.out.println(String.format("%d days %d hours %d minutes %d seconds", day, hour, minute, second));
19    }
20}
  1. 从键盘输入两个空格隔开的四位数,找到所有满足特殊条件的四位数字。例如1234是一个特殊的四位数,它各个位数之和为10,编程求出所有给定范围里所有特殊的四位数。输出的数字顺序从小到大。输出格式如图所示。每输出5个数字换行一次。
 1example:
 2
 3input:
 41000 1500
 5
 6output:
 71009 1018 1027 1036 1045
 81054 1063 1072 1081 1090
 91108 1117 1126 1135 1144
101153 1162 1171 1180 1207
111216 1225 1234 1243 1252
121261 1270 1306 1315 1324
131333 1342 1351 1360 1405
141414 1423 1432 1441 1450
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.List;
 5import java.util.ArrayList;
 6import java.util.stream.Collectors;
 7
 8public class Main {
 9    public static void main(String[] args) {
10        Scanner sc = new Scanner(System.in);
11        int a = sc.nextInt();
12        int b = sc.nextInt();
13        sc.close();
14
15        List<Integer> specialNumbers = new ArrayList<>();
16        for (int i = a; i <= b; i++) {
17            if (isSpecial(i)) {
18                specialNumbers.add(i);
19            }
20        }
21
22        for (int i = 0; i < specialNumbers.size(); i += 5) {
23            List<Integer> row = specialNumbers.subList(i, Math.min(i + 5, specialNumbers.size()));
24            String result = row.stream().map(String::valueOf).collect(Collectors.joining(" "));
25            System.out.println(result);
26        }
27    }
28
29    public static boolean isSpecial(int n) {
30        return n / 1000 + (n % 1000) / 100 + (n % 100) / 10 + n % 10 == 10;
31    }
32}
  1. 请编写一个程序,实现如下功能:读取一个整数序列,删除序列中连续重复数,输出结果序列。
1example:
2
3input:
41 2 2 1 5 1 1 7 7 7 7 1 1 1 1 1 1
5
6output:
71 2 1 5 1 7 1
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.Deque;
 5import java.util.LinkedList;
 6
 7public class Main {
 8    public static void main(String[] args) {
 9        Scanner sc = new Scanner(System.in);
10        String[] values = sc.nextLine().trim().split("\\s+");
11        sc.close();
12
13        Deque<String> deque = new LinkedList<>();
14        for (String value : values) {
15            if (!value.equals(deque.peekLast())) {
16                deque.addLast(value);
17            }
18        }
19
20        while (!deque.isEmpty()) {
21            System.out.print(deque.removeFirst() + " ");
22        }
23    }
24}
  1. 请编写程序,实现以下功能,从键盘输入一个n,创建一个n行n列的布尔型方阵。满足以下条件:如果i和j互素(即两者没有共同因子),则a[i][j]为1,否则为0。打印输出该布尔型矩阵。注意:0与任何数均不互素。
1example:
2
3input:
43
5
6output:
70 0 0 
80 1 1 
90 1 0
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        Scanner sc = new Scanner(System.in);
 8        int n = sc.nextInt();
 9        sc.close();
10
11        for (int i = 0; i < n; i++) {
12            for (int j = 0; j < n; j++) {
13                if (i == 0 || j == 0) {
14                    System.out.print("0 ");
15                } else {
16                    System.out.print(gcd(i, j) == 1 ? "1 " : "0 ");
17                }
18            }
19            System.out.println();
20        }
21    }
22
23    public static int gcd(int a, int b) {
24        return b == 0 ? a : gcd(b, a % b);
25    }
26}
  1. 从键盘输入一个n,代表布尔矩阵的行数。依次读入两个n行空格隔开的数字字符串,将两个n阶方阵转换成布尔矩阵(一定要先转换成布尔矩阵。即将非0的数字变为1,数字为0保持不变。)从键盘读入一个符号 +*,进行矩阵加法和矩阵乘法运算,(注意:这里的 +* 代表布尔运算的逻辑加和逻辑乘,逻辑加的运算规则为:1+1=1, 1+0=1, 0+1=1, 0+0=0,逻辑乘的运算规则为 1*1=1, 1*0=0, 0*1=0, 0*0=0。)输出结果同样为一个布尔型矩阵。(假设每一行录入的空格隔开的数字字符均为n个)
 1example:
 2
 3input:
 42
 51 0 
 61 1
 70 0 
 81 0
 9+
10
11output:
121 0 
131 1
14
15input:
162
171 0 
181 1
190 0 
201 0
21*
22
23output:
240 0 
251 0
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        Scanner sc = new Scanner(System.in);
 8        int n = sc.nextInt();
 9
10        boolean[][] aMatrix = new boolean[n][n];
11        boolean[][] bMatrix = new boolean[n][n];
12        for (int i = 0; i < n; i++) {
13            for (int j = 0; j < n; j++) {
14                int value = sc.nextInt();
15                aMatrix[i][j] = value != 0;
16            }
17        }
18        for (int i = 0; i < n; i++) {
19            for (int j = 0; j < n; j++) {
20                int value = sc.nextInt();
21                bMatrix[i][j] = value != 0;
22            }
23        }
24
25        sc.nextLine();
26        char operator = sc.nextLine().charAt(0);
27        sc.close();
28
29        boolean[][] result = new boolean[n][n];
30        switch (operator) {
31            case '+':
32                result = matrixAddition(aMatrix, bMatrix, n);
33                break;
34            case '*':
35                result = matrixMultiplication(aMatrix, bMatrix, n);
36                break;
37            default:
38                System.out.println("Invalid operator");
39                return;
40        }
41
42        for (int i = 0; i < n; i++) {
43            for (int j = 0; j < n; j++) {
44                System.out.print(result[i][j] ? "1 " : "0 ");
45            }
46            System.out.println();
47        }
48    }
49
50    public static boolean[][] matrixAddition(boolean[][] aMatrix, boolean[][] bMatrix, int n) {
51        boolean[][] result = new boolean[n][n];
52        for (int i = 0; i < n; i++) {
53            for (int j = 0; j < n; j++) {
54                result[i][j] = aMatrix[i][j] || bMatrix[i][j];
55            }
56        }
57        return result;
58    }
59
60    public static boolean[][] matrixMultiplication(boolean[][] aMatrix, boolean[][] bMatrix, int n) {
61        boolean[][] result = new boolean[n][n];
62        for (int i = 0; i < n; i++) {
63            for (int j = 0; j < n; j++) {
64                for (int k = 0; k < n; k++) {
65                    result[i][j] = result[i][j] || (aMatrix[i][j] && bMatrix[i][j]); // 没有 ||= 运算符
66                }
67            }
68        }
69        return result;
70    }
71}
  1. 用递归的方式生成n位的格雷码。所谓格雷码的规则为:对于n+1位的编码,先对n位编码按照顺序前面依次加0,生成0开头的n+1位编码,再对n位编码逆序,前面加1,生成1开头的n+1位编码。例如:一位编码为0和1,则二位编码,首先在0和1前面加0,生成00,01两个编码,然后对0和1进行逆序,得到1和0,前面加1,得到新的两位编码为11,10。从而生成所有的二位编码。

从键盘输出一个n,生成n位所有编码,并将编码存储在一个一维数组中输出。

 1example:
 2
 3input:
 41
 5
 6output:
 7['0', '1']
 8
 9input:
102
11
12output:
13['00', '01', '11', '10']
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.Arrays;
 5
 6public class Main {
 7    public static void main(String[] args) {
 8        Scanner sc = new Scanner(System.in);
 9        int n = sc.nextInt();
10        sc.close();
11
12        String[] gray = new String[(int) Math.pow(2, n)];
13        for (int i = 0; i < gray.length; i++) {
14            gray[i] = getGrayCode(i, n);
15        }
16        System.out.println(Arrays.toString(gray));
17    }
18
19    public static String getGrayCode(int n, int length) {
20        int gray = n ^ (n >> 1); // 错位异或得到格雷码
21        return String.format("%" + length + "s", Integer.toBinaryString(gray)).replace(' ', '0');
22    }
23}
  1. 从键盘接收一个整数,判断一下该整数是奇数还是偶数,如果是奇数,输出“odd",如果是偶数,输出“even”
1example:
2
3input:
420
5
6output:
7even
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        try (Scanner sc = new Scanner(System.in)) {
 8            System.out.println(sc.nextInt() % 2 == 0 ? "even" : "odd");
 9        }
10    }
11}
  1. 考虑我国的税务制度,采用分级制度,全年应纳税所得额不超过36000元的,税率3%,超过36000不超过144000元的部分,税率为10%,全年所得额超过144000不超过300000的部分,税率为20%,全年应纳税所得额超过300000不超过420000的部分,税率为25%。超过420000税率30%

从键盘输入一个人的全年总收入,计算他的个人所得税金额及剩余全年总收入。

1example:
2
3input:
440000
5
6output:
71120.0 38880.0
 1// 样例输出错了
 2package com.jackgdn;
 3
 4import java.util.Scanner;
 5
 6public class Main {
 7    public static void main(String[] args) {
 8        double raw;
 9        try (Scanner sc = new Scanner(System.in)) {
10            raw = sc.nextDouble();
11        }
12
13        double tax = 0, income = raw;
14        if (income > 420000) {
15            tax += (income - 420000) * 0.3;
16            income = 420000;
17        }
18        if (income > 300000) {
19            tax += (income - 300000) * 0.25;
20            income = 300000;
21        }
22        if (income > 144000) {
23            tax += (income - 144000) * 0.2;
24            income = 144000;
25        }
26        if (income > 36000) {
27            tax += (income - 36000) * 0.1;
28            income = 36000;
29        }
30        if (income > 0) {
31            tax += income * 0.03;
32        }
33
34        System.out.println(String.format("%.2f %.2f", tax, income - tax));
35    }
36}
  1. 从键盘输入一个代表年份的四位数,判断一下当前输入的年份是不是闰年,是闰年返回“is leap year”,不是闰年返回“is not leap year”
1example:
2
3input:
42024
5
6output:
7is leap year
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        try (Scanner sc = new Scanner(System.in)) {
 8            int year = sc.nextInt();
 9            if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
10                System.out.println(String.format("$d is a leap year"));
11            } else {
12                System.out.println(String.format("$d is not a leap year"));
13            }
14        }
15    }
16}
  1. 从键盘读入一组数据,用“#”结束。将读入的数据存在一维数组中,输出的一维数组为原一维数组每位的平方。
 1example:
 2
 3input:
 43
 54
 65
 76
 8#
 9
10output:
11[9, 16, 25, 36]
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.List;
 5import java.util.ArrayList;
 6
 7public class Main {
 8    public static void main(String[] args) {
 9        try (Scanner sc = new Scanner(System.in)) {
10            List<Integer> nums = new ArrayList<>();
11            String input;
12            while (!(input = sc.nextLine()).equals("#")) { // 在赋值时计算
13                nums.add((int) Math.pow(Integer.parseInt(input), 2));
14            }
15            System.out.println(nums);
16        }
17    }
18}
  1. 从键盘读入一组空格分隔的数字字符,将这些数字字符转换为数值类型存储在一个一维数组中。判断一下该一组数组中存的数是不是单调递增的。单调递增的概念是对于一维数组list1而言,list1[i] <= list1[i + 1]。如果该一维数组是单调递增的返回True,否则返回False。注:空格隔开的数字字符中不包括小数点。
1example:
2
3input:
41 3 5 7 9
5
6output:
7True
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        try (Scanner sc = new Scanner(System.in)) {
 8            int previous = Integer.MIN_VALUE, current = Integer.MIN_VALUE;
 9            while (sc.hasNextInt()) { // hasNextInt() 以 ^Z 或 ^D 结束输入(需要 EOF)
10                previous = current;
11                current = sc.nextInt();
12                if (previous > current) {
13                    System.out.println(false);
14                    return;
15                }
16            }
17            System.out.println(true);
18        }
19    }
20}
  1. 从键盘接收一组空格隔开的数字字符,将他们存储在一个一位数组中。删除其中包含字符"5"的字符串,并将其中能转换成数字字符,能被5整除的也删掉。
1example:
2
3input:
412345 21532 55123 14268 10000
5
6output:
7['14268']
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.List;
 5import java.util.ArrayList;
 6
 7public class Main {
 8    public static void main(String[] args) {
 9        try (Scanner sc = new Scanner(System.in)) {
10            List<Integer> result = new ArrayList<>();
11            String[] numStringArray = sc.nextLine().trim().split("\\s+");
12            for (String numString : numStringArray) {
13                if (!numString.contains("5") && !(numString.charAt(numString.length() - 1) == '0')) {
14                    result.add(Integer.parseInt(numString));
15                }
16            }
17            System.out.println(result);
18        }
19    }
20}
  1. 从键盘接收一个长字符串,输出里面包含的元音字符的个数。(注意:大小写的元音字符都要统计)
1example:
2
3input:
4aibie
5
6output:
74
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        try (Scanner sc = new Scanner(System.in)) {
 8            String s = sc.nextLine();
 9            int count = 0;
10            for (char c : s.toCharArray()) {
11                if ("aeiouAEIOU".contains(String.valueOf(c))) {
12                    count++;
13                }
14            }
15            System.out.println(count);
16        }
17    }
18}
  1. 从键盘接收一个空格隔开的数字字符,并把它们转换为int类型数据存在一个一维数组中,统计一下其中素数的个数。如果没有任何素数,返回0.
 1example:
 2
 3input:
 41 3 5 7 9
 5
 6output:
 71 3 5 7 9
 83
 9
10input:
112 4 6 8 10
12
13output:
141
  1. 从键盘接收一个空格隔开的数字字符,并把它们转换为int类型数据存在一个一维数组中,统计一下其中素数的个数。如果没有任何素数,返回0.
 1example:
 2
 3input:
 41 3 5 7 9
 5
 6output:
 71 3 5 7 9
 83
 9
10input:
112 4 6 8 10
12
13output:
141
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.List;
 5import java.util.Arrays;
 6import java.util.stream.Collectors;
 7
 8public class Main {
 9    public static void main(String[] args) {
10        try (Scanner sc = new Scanner(System.in)) {
11            int count = 0;
12            List<Integer> nums = Arrays.stream(sc.nextLine().trim().split("\\s+"))
13                    .map(Integer::parseInt)
14                    .collect(Collectors.toList());
15            for (int num : nums) {
16                if (isPrime(num)) {
17                    count++;
18                }
19            }
20            System.out.println(count);
21        }
22    }
23
24    public static boolean isPrime(int n) {
25        if (n <= 1) {
26            return false;
27        }
28        for (int i = 2; i * i <= n; i++) {
29            if (n % i == 0) {
30                return false;
31            }
32        }
33        return true;
34    }
35}
  1. 从键盘输入一个n,生成一个n*n的二维数组,二维数组为一个单位矩阵。即除主对角线全为1外,其余部分全为0.按行打印二维数组如example所示。
1example:
2
3input:
43
5
6output:
7[1, 0, 0]
8[0, 1, 0]
9[0, 0, 1]
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.Arrays;
 5
 6public class Main {
 7    public static void main(String[] args) {
 8        try (Scanner sc = new Scanner(System.in)) {
 9            int n = sc.nextInt();
10            int[][] matrix = new int[n][n];
11            for (int i = 0; i < n; i++) {
12                for (int j = 0; j < n; j++) {
13                    matrix[i][j] = i == j ? 1 : 0;
14                }
15                System.out.println(Arrays.toString(matrix[i]));
16            }
17        }
18    }
19}

系列文章