Java 练习(五)
- 从键盘输入一个m,代表二维矩阵A的行和列,然后输入m行数据,每行数据用空格分割。再输入一个n,代表矩阵的幂运算次数,即n = 2输出A * A 的值。n = 3 输出A * A *A的值。
1example:
2
3input:
42
51 1
61 1
72
8
9output:
10[[2, 2], [2, 2]]
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 scanner = new Scanner(System.in);
9 int order = scanner.nextInt();
10 int[][] matrix = new int[order][order];
11 for (int i = 0; i < order; i++) {
12 for (int j = 0; j < order; j++) {
13 matrix[i][j] = scanner.nextInt();
14 }
15 }
16 int power = scanner.nextInt();
17 scanner.close();
18
19 int[][] result = matrixPower(matrix, power, order);
20 System.out.println(Arrays.deepToString(result));
21 }
22
23 public static int[][] matrixPower(int[][] matrix, int power, int order) {
24 if (power == 1) {
25 return matrix;
26 }
27
28 int[][] result = matrix;
29 while (power > 1) {
30 result = matrixMultiply(result, matrix, order);
31 power--;
32 }
33 return result;
34 }
35
36 public static int[][] matrixMultiply(int[][] aMatrix, int[][] bMatrix, int order) {
37 int[][] result = new int[order][order];
38 for (int i = 0; i < order; i++) {
39 for (int j = 0; j < order; j++) {
40 for (int k = 0; k < order; k++) {
41 result[i][j] += aMatrix[i][k] * bMatrix[k][j];
42 }
43 }
44 }
45 return result;
46 }
47}
- 从键盘输入一个十进制的长整数,计算各位数字的和。
1example:
2
3input
4123456789
5
6output:
745
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 String numString = scanner.nextLine();
9 scanner.close();
10
11 int sum = 0;
12 for (int i = 0; i < numString.length(); i++) {
13 sum += Character.getNumericValue(numString.charAt(i)); // Character.getNumericValue() 将 char 转化为 int
14 }
15
16 System.out.println(sum);
17 }
18}
- 输入一行由两个四位数和空格隔开的字符串,区间[a,b],其中a为前面四位数,b为空格后面的四位数。计算a—b范围内所有四位数每个位数的和,将位数和为10的四位数输出出来。(例:1234每一位做加法,就是1+2+3+4 = 10)并用try,except结构,对输入数据进行判断,如果不能转换为int型数据,输出"Input Error!".
1example:
2
3input:
41000 1050
5
6output:
7[1009,1018, 1027, 1036, 1045]
8
9input:
1010a
11
12output:
13Input Error!
1package com.jackgdn;
2
3import java.util.Scanner;
4import java.util.List;
5import java.util.ArrayList;
6import java.util.InputMismatchException;
7
8public class Main {
9 public static void main(String[] args) {
10 try (Scanner scanner = new Scanner(System.in)) {
11 int a = scanner.nextInt();
12 int b = scanner.nextInt();
13
14 List<Integer> result = new ArrayList<>();
15 for (int i = a; i <= b; i++) {
16 if (digitSum(i) == 10) {
17 result.add(i);
18 }
19 }
20
21 System.out.println(result);
22 } catch (InputMismatchException e) {
23 System.out.println("Input Error!");
24 }
25 }
26
27 public static int digitSum(int n) {
28 return n / 1000 + (n % 1000) / 100 + (n % 100) / 10 + n % 10;
29 }
30}
- 从键盘接受一行字符串,将字符串中不同的字符添加在一个一维数组中。并按照字符的ASCII从小到大排序。(区分大小写,“A”和“a”是不同字符)
1example:
2
3input:
4
5aidieAQie230 2s
6
7output:
8
9['A', 'Q', 'a', 'd', 'e', 'i', 's']
1package com.jackgdn;
2
3import java.util.Scanner;
4import java.util.TreeSet; // 使用 TreeSet 保持有序
5
6public class Main {
7 public static void main(String[] args) {
8 TreeSet<Character> list = new TreeSet<>();
9
10 try (Scanner scanner = new Scanner(System.in)) {
11 String input = scanner.nextLine();
12 for (char c : input.toCharArray()) {
13 if (Character.isLetter(c)) {
14 list.add(c);
15 }
16 }
17 }
18
19 System.out.println(list);
20 }
21}
- 编写函数,接收字符串参数,返回一个元组,其中第一个元素为小写字母个数,第二个元素为大写字母个数。
1input:
2diwoULNidieoJIOJOdie
3
4output:
5(12, 8)
1package com.jackgdn;
2
3import java.util.Scanner;
4
5public class Main {
6 public static void main(String[] args) {
7 int lowerCount = 0, upperCount = 0;
8 try (Scanner scanner = new Scanner(System.in)) {
9 String input = scanner.nextLine();
10 for (char c : input.toCharArray()) {
11 if (Character.isLowerCase(c)) {
12 lowerCount++;
13 } else if (Character.isUpperCase(c)) {
14 upperCount++;
15 }
16 }
17 }
18 System.out.println(String.format("(%d, %d)", lowerCount, upperCount));
19 }
20}
- 编写一个程序,从键盘接受一组空格隔开的单词,统计每个单词和它出现的次数,并存在一个元组中。将此元组作为字典的键,单词中元音单词的个数做为值存在一个字典中。(注:单词区分大小写)
1input:
2
3hello hello hello world world A
4
5ouput:
6
7{('hello', 3): 2, ('world', 2): 1, ('A', 1): 1}
1package com.jackgdn;
2
3import java.util.Scanner;
4import java.util.Map;
5import java.util.HashMap;
6import java.util.Arrays;
7
8public class Main {
9 public static void main(String[] args) {
10 Scanner scanner = new Scanner(System.in);
11 String input = scanner.nextLine();
12 scanner.close();
13
14 String[] words = input.trim().split(" +");
15 Map<String, Integer[]> initMap = new HashMap<>();
16 for (String word : words) {
17 Integer[] value = initMap.getOrDefault(word, new Integer[] { 0, countVowels(word) }); // getOrDefault()
18 // 方法返回指定键的值,如果不存在则返回默认值
19 value[0]++;
20 initMap.put(word, value);
21 }
22
23 Map<String, Integer> resultMap = new HashMap<>();
24 for (Map.Entry<String, Integer[]> entry : initMap.entrySet()) {
25 String[] keyArray = new String[] { entry.getKey(), String.valueOf(entry.getValue()[0]) };
26 String key = Arrays.toString(keyArray);
27 int value = entry.getValue()[1];
28 resultMap.put(key, value);
29 }
30
31 System.out.println(resultMap);
32 }
33
34 public static int countVowels(String word) {
35 int count = 0;
36 for (char c : word.toCharArray()) {
37 if ("aeiouAEIOU".indexOf(c) != -1) { // String.contains() 参数为 CharSequence 类型,不支持 char 类型
38 count++;
39 }
40 }
41 return count;
42 }
43}
- 问题描述
首先给出简单加法算式的定义: 如果有一个算式(i)+(i+1)+(i+2),(i>=0),在计算的过程中,没有任何一个数位出现了进位,则称其为简单的加法算式。 例如:i=3时,3+4+5=12,有一个进位,因此3+4+5不是一个简单的加法算式;又如i=112时,112+113+114=339,没有在任意数位上产生进位,故112+113+114是一个简单的加法算式。
问题:给定一个正整数n,问当i大于等于0且小于n时,有多少个算式(i)+(i+1)+(i+2)是简单加法算式。其中n<10000。
输入格式
一个整数,表示n
输出格式
一个整数,表示简单加法算式的个数
注意:我们要求的简单加法进位,只要求最终结果的位数不超过i的位数,不限制内部数字做加法是否有进位。
1input:
24
3
4output:
53
1// 这道题让我与满绩擦肩而过 ┭┮﹏┭┮
2package com.jackgdn;
3
4import java.util.Scanner;
5
6public class Main {
7 public static void main(String[] args) {
8 int n;
9 try (Scanner scanner = new Scanner(System.in)) {
10 n = scanner.nextInt();
11 }
12
13 int count = 0;
14 for (int i = 0; i < n; i++) {
15 if (hasSimpleAddition(i)) {
16 System.out.print(i + " ");
17 count++;
18 }
19 }
20
21 System.out.println(count);
22 }
23
24 public static boolean hasSimpleAddition(int n) {
25 if (n - n / 10 * 10 > 2) {
26 return false;
27 }
28
29 while (n / 10 != 0) {
30 n /= 10;
31 if (n - n / 10 * 10 > 3) {
32 return false;
33 }
34 }
35
36 return true;
37 }
38}
- 有red, green, blue, yellow, white和black六种颜色的气球若干。现在飘过来一大堆不同颜色的气球,请你用字典实现对不用颜色的气球计数(键为字符串,值为计数)。
输入以“#”表示结束,若未出现相应颜色的字符串则忽略;反之,则计数。
按字典序(字母升序)实现对键值对的输出。
1比如输入为:
2red
3green
4blue
5yellow
6white
7#
8
9则输出为:
10black 0
11blue 1
12green 1
13red 1
14white 1
15yellow 1
1package com.jackgdn;
2
3import java.util.Scanner;
4import java.util.Map;
5import java.util.TreeMap;
6
7public class Main {
8 public static void main(String[] args) {
9 Map<String, Integer> map = new TreeMap<>();
10 for (String s : new String[] { "red", "green", "blue", "yellow", "white", "black" }) {
11 map.put(s, 0);
12 }
13
14 Scanner scanner = new Scanner(System.in);
15 String baloon = scanner.nextLine();
16 while (!baloon.equals("#")) {
17 map.put(baloon, map.get(baloon) + 1);
18 baloon = scanner.nextLine();
19 }
20 scanner.close();
21
22 for (Map.Entry<String, Integer> entry : map.entrySet()) {
23 String key = entry.getKey();
24 int value = entry.getValue();
25 System.out.println(key + " " + value);
26 }
27 }
28}
- 从键盘输入一个数字(正整数),判断需要加多少次,可以得到一个回文数字,例如:输入56,则56 + 65 =121为一个回文数字。
又如:对于十进制数
8787
87:
STEP1:
87+78=165
STEP2:
165+561=726
STEP3:
726+627=1353
STEP4:
1353+3531=4884
需四步得到一个回文数字。如果超过30步,则输出Impossible!
1input:
265
3
4output:
5huiwen need 1 iterate,and huiwen number is 121.
6
7input:
887
9
10output:
11huiwen need 4 iterate,and huiwen number is 4884.
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 int n = scanner.nextInt();
9 scanner.close();
10
11 for (int i = 0; i < 30; i++) {
12 if (isPalindrome(n)) {
13 System.out.println(String.format("After %d iterations, the palindrome number %d is obtained.", i, n));
14 return;
15 }
16 n = n + reverse(n);
17 }
18 System.out.println("Impossible.");
19 }
20
21 public static boolean isPalindrome(int n) {
22 String num = String.valueOf(n);
23 int left = 0;
24 int right = num.length() - 1;
25 while (left < right) {
26 if (num.charAt(left) != num.charAt(right)) {
27 return false;
28 }
29 left++;
30 right--;
31 }
32 return true;
33 }
34
35 public static int reverse(int n) {
36 String num = String.valueOf(n);
37 String reversed = new StringBuilder(num).reverse().toString(); // 倒置字符串
38 return Integer.parseInt(reversed);
39 }
40}
- 试写一个函数,输入日、月、年,并按如下两种格式分别输出:
Standard format: yyyy-mm-dd
New Zealand format: dd/mm/yyyy
1比如输入为:
26
37
41976
5
6则输出为:
7Standard format: 1976-07-06
8New Zealand format: 06/07/1976
1package com.jackgdn;
2
3import java.util.Scanner;
4
5public class Main {
6 public static void main(String[] args) {
7 try (Scanner scanner = new Scanner(System.in)) {
8 int day = scanner.nextInt();
9 int month = scanner.nextInt();
10 int year = scanner.nextInt();
11 System.out.println(String.format("Standard format: %d-%02d-%02d", year, month, day)); // %0 表示用 0 补齐
12 System.out.println(String.format("New Zealand format: %02d/%02d/%d", day, month, year));
13 }
14 }
15}
- 从键盘输入一组数字组成的字符串,再输入一个指定的数字,删除字符串中所有指定的数字,并将结果存在列表中输出。
1input:
23742484 1736364 38599483486
33
4
5output:
6['742484', '17664', '859948486']
7
8input:
93742484 1736364 38599483486
104
11
12output:
13['3728', '173636', '385998386']
1package com.jackgdn;
2
3import java.util.Scanner;
4import java.util.List;
5import java.util.ArrayList;
6import java.util.Arrays;
7
8public class Main {
9 public static void main(String[] args) {
10 try (Scanner scanner = new Scanner(System.in)) {
11 String[] nums = scanner.nextLine().trim().split("\\s+");
12 String x = scanner.nextLine().trim();
13
14 /*
15 * 将一个 String[] 中的每一个元素经过 exlude() 函数处理后,存储到一个 ArrayList<String> 中,
16 * 使用 Stream 接口的 toList() 方法会得到一个不可变的 List,
17 * 使用 collect(Collectors.toList()) 可以获得可变的 List。
18 */
19 List<String> result = new ArrayList<>(Arrays.stream(nums).map(num -> exclude(num, x)).toList());
20 System.out.println(result);
21 }
22 }
23
24 public static String exclude(String num, String x) {
25 List<String> digits = new ArrayList<>(Arrays.stream(num.split("")).toList());
26 digits.removeIf(d -> d.equals(x)); // 使用 for 遍历 List 时删除元素会导致异常
27 return String.join("", digits);
28 }
29}
- 输入一个用空格隔开的两个数字字符串,将给定范围内,所有成对的反素数,按从小到大的顺序组成一个元组,存入到列表中。反素数:17 和 71既是反素数。注意,回文素数不是反素数,171既是回文素数。
1input:
210 100
3
4output:
5[(13, 31), (17, 71), (37, 73), (79, 97)]
1package com.jackgdn;
2
3import java.util.Scanner;
4import java.util.List;
5import java.util.ArrayList;
6import java.util.Arrays;
7
8public class Main {
9 public static void main(String[] args) {
10 Scanner scanner = new Scanner(System.in);
11 int a = scanner.nextInt();
12 int b = scanner.nextInt();
13 scanner.close();
14
15 List<int[]> result = new ArrayList<>();
16 int reversed;
17 for (int i = a; i <= b; i++) {
18 if (isPrime(i) && !isPalindrome(i)) {
19 reversed = reverse(i);
20 if (reversed > i && isPrime(reversed)) {
21 result.add(new int[] { i, reversed });
22 }
23 }
24 }
25
26 System.out.println(Arrays.deepToString(result.toArray()));
27 }
28
29 public static boolean isPrime(int n) {
30 if (n <= 1) {
31 return false;
32 }
33 for (int i = 2; i * i <= n; i++) {
34 if (n % i == 0) {
35 {
36 return false;
37 }
38 }
39 }
40 return true;
41 }
42
43 public static boolean isPalindrome(int n) {
44 String num = String.valueOf(n);
45 int left = 0;
46 int right = num.length() - 1;
47 while (left < right) {
48 if (num.charAt(left) == num.charAt(right)) {
49 left++;
50 right--;
51 } else {
52 return false;
53 }
54 }
55 return true;
56 }
57
58 public static int reverse(int n) {
59 String num = String.valueOf(n);
60 StringBuilder sb = new StringBuilder(num);
61 sb.reverse();
62 return Integer.parseInt(sb.toString());
63 }
64}
- s串初始为"0,按以下方式变:0变1,1变01
输入格式
1个整数(0~19)
输出格式
n次变换后s01串
1input:
23
3
4output:
5101
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 int n = scanner.nextInt();
9 scanner.close();
10
11 if (n == 0) {
12 System.out.println("0");
13 return;
14 }
15
16 String s = "0";
17 for (int i = 0; i < n; i++) {
18 StringBuilder nextString = new StringBuilder();
19 for (char c : s.toCharArray()) {
20 nextString.append(c == '0' ? "1" : "01");
21 }
22 s = nextString.toString();
23 }
24 System.out.println(s);
25 }
26}
- 定义一个NewTuple类,能够实现两个元组类的+,-,*,//运算,已知两个元组中包含元素个数相同,对/和//,判断余数中是否有0,如果出现除数为0的情况,输出“The divisor cannot be zero. ”其他情况,按照按位加减乘除(注:除非只需要完成整除运算)的原则运算即可。(类中加减乘除的方法名分别为:add;sub;mul;floordiv)
从键盘输入三行数据,第一行和第二行为两个需要计算的元组,第三行为计算的符号(即:+,-,*,//)输出计算后得到的新元组的类型和计算后得到的新元组。
1example:
2
3input:
4(1,2,3)
5(4,5,6)
6*
7
8output:
9(4, 10, 18)
1/* 这是 NewTuple.java 的代码,
2 * 其中使用了泛型,因此看上去比较复杂。
3 * 检测输入输出类型对我来说还是有些困难。
4 */
5package com.jackgdn;
6
7import java.util.List;
8
9public class NewTuple<T extends Number> {
10 public List<T> values;
11
12 public NewTuple() {
13 }
14
15 public NewTuple(List<T> values) {
16 this.values = values;
17 }
18
19 public int size() {
20 return values.size();
21 }
22
23 public NewTuple<T> add(NewTuple<T> other) {
24 for (int i = 0; i < Math.min(this.size(), other.size()); i++) {
25 Number thisValue = this.values.get(i);
26 Number otherValue = other.values.get(i);
27
28 if (thisValue instanceof Integer) {
29 this.values.set(i, (T) (Number) (thisValue.intValue() + otherValue.intValue()));
30 } else if (thisValue instanceof Double) {
31 this.values.set(i, (T) (Number) (thisValue.doubleValue() + otherValue.doubleValue()));
32 } else if (thisValue instanceof Float) {
33 this.values.set(i, (T) (Number) (thisValue.floatValue() + otherValue.floatValue()));
34 } else if (thisValue instanceof Long) {
35 this.values.set(i, (T) (Number) (thisValue.longValue() + otherValue.longValue()));
36 } else if (thisValue instanceof Short) {
37 this.values.set(i, (T) (Number) (thisValue.shortValue() + otherValue.shortValue()));
38 } else if (thisValue instanceof Byte) {
39 this.values.set(i, (T) (Number) (thisValue.byteValue() + otherValue.byteValue()));
40 } else {
41 throw new UnsupportedOperationException();
42 }
43 }
44
45 return this;
46 }
47
48 public NewTuple<T> sub(NewTuple<T> other) {
49 for (int i = 0; i < Math.min(this.size(), other.size()); i++) {
50 Number thisValue = this.values.get(i);
51 Number otherValue = other.values.get(i);
52
53 if (thisValue instanceof Integer) {
54 this.values.set(i, (T) (Number) (thisValue.intValue() - otherValue.intValue()));
55 } else if (thisValue instanceof Double) {
56 this.values.set(i, (T) (Number) (thisValue.doubleValue() - otherValue.doubleValue()));
57 } else if (thisValue instanceof Float) {
58 this.values.set(i, (T) (Number) (thisValue.floatValue() - otherValue.floatValue()));
59 } else if (thisValue instanceof Long) {
60 this.values.set(i, (T) (Number) (thisValue.longValue() - otherValue.longValue()));
61 } else if (thisValue instanceof Short) {
62 this.values.set(i, (T) (Number) (thisValue.shortValue() - otherValue.shortValue()));
63 } else if (thisValue instanceof Byte) {
64 this.values.set(i, (T) (Number) (thisValue.byteValue() - otherValue.byteValue()));
65 } else {
66 throw new UnsupportedOperationException();
67 }
68 }
69
70 return this;
71 }
72
73 public NewTuple<T> mul(NewTuple<T> other) {
74 for (int i = 0; i < Math.min(this.size(), other.size()); i++) {
75 Number thisValue = this.values.get(i);
76 Number otherValue = other.values.get(i);
77
78 if (thisValue instanceof Integer) {
79 this.values.set(i, (T) (Number) (thisValue.intValue() * otherValue.intValue()));
80 } else if (thisValue instanceof Double) {
81 this.values.set(i, (T) (Number) (thisValue.doubleValue() * otherValue.doubleValue()));
82 } else if (thisValue instanceof Float) {
83 this.values.set(i, (T) (Number) (thisValue.floatValue() * otherValue.floatValue()));
84 } else if (thisValue instanceof Long) {
85 this.values.set(i, (T) (Number) (thisValue.longValue() * otherValue.longValue()));
86 } else if (thisValue instanceof Short) {
87 this.values.set(i, (T) (Number) (thisValue.shortValue() * otherValue.shortValue()));
88 } else if (thisValue instanceof Byte) {
89 this.values.set(i, (T) (Number) (thisValue.byteValue() * otherValue.byteValue()));
90 } else {
91 throw new UnsupportedOperationException();
92 }
93 }
94
95 return this;
96 }
97
98 public NewTuple<T> div(NewTuple<T> other) {
99 for (int i = 0; i < Math.min(this.size(), other.size()); i++) {
100 if (other.values.get(i).doubleValue() == 0.0) {
101 throw new ArithmeticException("/ by zero");
102 }
103 }
104
105 for (int i = 0; i < Math.min(this.size(), other.size()); i++) {
106 Number thisValue = this.values.get(i);
107 Number otherValue = other.values.get(i);
108
109 if (thisValue instanceof Integer) {
110 this.values.set(i, (T) (Number) (thisValue.intValue() / otherValue.intValue()));
111 } else if (thisValue instanceof Double) {
112 this.values.set(i, (T) (Number) (thisValue.doubleValue() / otherValue.doubleValue()));
113 } else if (thisValue instanceof Float) {
114 this.values.set(i, (T) (Number) (thisValue.floatValue() / otherValue.floatValue()));
115 } else if (thisValue instanceof Long) {
116 this.values.set(i, (T) (Number) (thisValue.longValue() / otherValue.longValue()));
117 } else if (thisValue instanceof Short) {
118 this.values.set(i, (T) (Number) (thisValue.shortValue() / otherValue.shortValue()));
119 } else if (thisValue instanceof Byte) {
120 this.values.set(i, (T) (Number) (thisValue.byteValue() / otherValue.byteValue()));
121 } else {
122 throw new UnsupportedOperationException();
123 }
124 }
125
126 return this;
127 }
128
129 public String toString() {
130 return values.toString();
131 }
132}
- 重新定义一个str类,使其可以完成加法和减法的操作。其中加法操作执行如下:"abcdefg" + "acdi" = "abcdefgi"即把加号后面的字符串没出现在前面字符串中的字符连接到字符串后面得到的新字符串为加法运算的结果。"abcdefg" - "acdi" = "befg"即把减号前面字符串去掉后面字符串中出现的字符剩余的字符为减法运算的结果。并可以对字符串做打印输出操作。
从键盘输入两行字符串,输出两行字符串的加法运算和减法运算后的值。
1example:
2
3input:
4abcdefg
5acdi
6
7output:
8abcdefgi
9befg
1// Main.java
2package com.jackgdn;
3
4import java.util.Scanner;
5
6public class Main {
7 public static void main(String[] args) {
8 Scanner scanner = new Scanner(System.in);
9 NewStr aStr = new NewStr(scanner.nextLine());
10 NewStr bStr = new NewStr(scanner.nextLine());
11 scanner.close();
12
13 NewStr cStr = aStr.copy();
14 aStr.addNoDuplicates(bStr);
15 cStr.removeDuplicates(bStr);
16
17 System.out.println(aStr);
18 System.out.println(cStr);
19 }
20}
21
22// NewStr.java
23package com.jackgdn;
24
25public class NewStr { // String 类是一个 final 类,不能被继承
26 public String value;
27
28 public NewStr() {
29 value = "";
30 }
31
32 public NewStr(String value) {
33 this.value = value;
34 }
35
36 public void addNoDuplicates(String s) {
37 StringBuilder sb = new StringBuilder(value);
38 for (char c : s.toCharArray()) {
39 if (value.indexOf(c) == -1) {
40 sb.append(c);
41 }
42 }
43 value = sb.toString();
44 }
45
46 public void addNoDuplicates(NewStr other) {
47 StringBuilder sb = new StringBuilder(this.value);
48 for (char c : other.value.toCharArray()) {
49 if (this.value.indexOf(c) == -1) {
50 sb.append(c);
51 }
52 }
53 this.value = sb.toString();
54 }
55
56 public void removeDuplicates(String s) {
57 StringBuilder sb = new StringBuilder();
58 for (char c : s.toCharArray()) {
59 int index = value.indexOf(c);
60 if (index != -1) {
61 sb.deleteCharAt(index);
62 }
63 }
64 value = sb.toString();
65 }
66
67 public void removeDuplicates(NewStr other) {
68 StringBuilder sb = new StringBuilder(this.value);
69 int offset = 0;
70 for (char c : other.value.toCharArray()) {
71 int index = this.value.indexOf(c);
72 if (index != -1) {
73 sb.deleteCharAt(index - offset); // StringBuilder 越来越短但是 this.value 长度不变,因此需要 offset 确保删掉正确的字符
74 offset++;
75 }
76 }
77 this.value = sb.toString();
78 }
79
80 public NewStr copy() {
81 return new NewStr(value);
82 }
83
84 @Override
85 public String toString() {
86 return value;
87 }
88}
- 从键盘输入一个m,n,代表二维数组的行和列,输入m行数据,每行数据一共n个,用空格隔开。查找行和列中包括的2023的个数。(m和n均大于等于4,m和n可以不相等,且同一行同一列中只能找到一个2023)。
1example:
2
3input:
44 4
52 0 2 3
60 2 0 2
72 0 2 3
83 3 3 1
9
10output:
114
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 int m = scanner.nextInt();
9 int n = scanner.nextInt();
10 scanner.nextLine();
11 int count = 0;
12 String[] arr = new String[m];
13 for (int i = 0; i < m; i++) {
14 arr[i] = scanner.nextLine();
15 if (arr[i].contains("2 0 2 3")) {
16 count++;
17 }
18 }
19 scanner.close();
20
21 for (int i = 0; i < 2 * n - 1; i++) {
22 StringBuilder sb = new StringBuilder();
23 for (int j = 0; j < m; j++) {
24 sb.append(arr[j].charAt(i));
25 }
26 String s = sb.toString();
27 if (s.contains("2023")) {
28 count++;
29 }
30 }
31
32 System.out.println(count);
33 }
34}
- 用泰勒级数展开求e的值。$e=1+\frac1{1!}+\frac1{2!}+\cdots+\frac1{n!}$,从键盘输入一个n,根据n值得不同,给出e的值。
1example:
2
3input:
410
5
6output:
72.7182818011463845
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 int n = scanner.nextInt();
9 scanner.close();
10
11 double e = series(n);
12 System.out.println(e);
13 }
14
15 public static double series(int n) {
16 double result = 0.0;
17 for (int i = 0; i <= n; i++) {
18 result += 1.0 / factorial(i);
19 }
20 return result;
21 }
22
23 public static int factorial(int n) {
24 if (n == 0) {
25 return 1;
26 } else {
27 int result = 1;
28 for (int i = 1; i <= n; i++) {
29 result *= i;
30 }
31 return result;
32 }
33 }
34}
- 输入一组字符串,字符串可能包括英文字符数字字符或者符号等,统计其中出现的每一个字符,及字符出现的次数,将字符和它出现次数存储在一个字典中。(注:区分大小写,即大写的A和小写的a不是一个字符)
1input:
2asuusea7472a
3
4output:
5{'a': 3, 's': 2, 'u': 2, 'e': 1, '7': 2, '4': 1, '2': 1}
1package com.jackgdn;
2
3import java.util.Scanner;
4import java.util.Map;
5import java.util.LinkedHashMap; // LinkedHashMap 保留插入序
6
7public class Main {
8 public static void main(String[] args) {
9 Scanner scanner = new Scanner(System.in);
10 String s = scanner.nextLine();
11 scanner.close();
12
13 Map<Character, Integer> result = new LinkedHashMap<>();
14 for (char c : s.toCharArray()) {
15 int count = result.getOrDefault(c, 0);
16 result.put(c, count + 1);
17 }
18
19 System.out.println(result);
20 }
21}
- 从键盘接收一个用空格隔开的长字符串,将字符串整理为按照单词首字母区分的字典,字典的键为大写字母,值为一个所有以此字母开头的单词列表。列表中不包括相同单词。
1input:
2why does someone believe you when you say
3
4ouput:
5{'W': ['why', 'when'], 'D': ['does'], 'S': ['someone', 'say'], 'B': ['believe'], 'Y': ['you']}
1package com.jackgdn;
2
3import java.util.Scanner;
4import java.util.Map;
5import java.util.Set;
6import java.util.LinkedHashMap;
7import java.util.LinkedHashSet;
8
9public class Main {
10 public static void main(String[] args) {
11 Scanner scanner = new Scanner(System.in);
12 String[] words = scanner.nextLine().trim().split("\\s+");
13 scanner.close();
14
15 Map<Character, Set<String>> result = new LinkedHashMap<>();
16 for (String word : words) {
17 Set<String> wordSet = result.getOrDefault(Character.toUpperCase(word.charAt(0)), new LinkedHashSet<>());
18 wordSet.add(word);
19 result.put(Character.toUpperCase(word.charAt(0)), wordSet);
20 }
21
22 System.out.println(result);
23 }
24}