import java.util.Arrays;import java.util.Scanner;public class SortString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); char[] chars = input.toCharArray(); // 将字符串转换为字符数组 Arrays.sort(chars); // 对字符数组进行排序 StringBuilder result = new StringBuilder(); int i = 0; while (i < chars.length) { int j = i + 1; while (j < chars.length && chars[j] == chars[i]) { j++; } result.append(chars[i]); i = j; } System.out.println(result.toString()); }}
时间: 2024-04-27 14:21:01 浏览: 13
这段代码从标准输入接收一个字符串输入,字符串由小写字母构成,将字符串中内容按字母表顺序排序后重新输出。若字符有重复则输出同等数量字符。如输入字符串“beaaoln”,则输出为“aabelno”。
这段代码是正确的,没有语法错误。它的主要思路是将输入的字符串转换为字符数组,然后对字符数组进行排序,最后遍历字符数组,如果发现相邻的字符相同,则跳过中间的字符,直接将结果添加到一个StringBuilder对象中。最后,将StringBuilder对象转换为字符串并输出。
相关问题
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
Arrays.sort(nums);
int maxCount = 0;
int currentCount = 1;
for (int i = 1; i < n; i++) {
if (nums[i] == nums[i-1]) {
currentCount++;
} else {
maxCount = Math.max(maxCount, currentCount);
currentCount = 1;
}
}
maxCount = Math.max(maxCount, currentCount);
System.out.println(maxCount);
}
}
import java.util.Scanner; import java.util.Arrays; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = input.nextInt(); } Arrays.sort(nums); for (int i = 0; i < n; i++) { System.out.print(nums[i] + " "); } } }修改这段代码,使其每个元素之间用一个空格隔开,但是最后一个元素后面没有空格
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = input.nextInt();
}
Arrays.sort(nums);
for (int i = 0; i < n; i++) {
System.out.print(nums[i]);
if (i != n - 1) {
System.out.print(" ");
}
}
}
}