package zifuchuan.caozuo; import java.util.Scanner; import java.util.TreeSet; public class ShuruZhengxingshuzuhepaixubiaoshi { public static void main(String[] args) { Scanner in = new Scanner(System.in); TreeSet<Integer> set = new TreeSet<>(); int count =Integer.parseInt(in.nextLine()); String[] arr = in.nextLine().split(" "); int flag = Integer.parseInt(in.nextLine()); System.out.println(flag); for (int i = 0; i < count; i++) { set.add(Integer.parseInt(arr[i] + "")); } Object[] arr1 = set.stream().sorted().toArray(); if (flag == 0) { for (int i = 0; i <= arr1.length - 1; i++) { if (i < arr1.length - 1) System.out.println(Integer.parseInt(arr1[i] + " ")); else System.out.println(Integer.parseInt(arr1[i] + "")); } }else if(flag == 1){ for (int i = arr1.length - 1; i >=0 ; i--) { if (i < arr1.length - 1) System.out.println(Integer.parseInt(arr1[i] + " ")); else System.out.println(Integer.parseInt(arr1[i] + "")); } } } } 哪里出了问题
时间: 2023-06-19 11:08:55 浏览: 137
在输出排序后的数组元素时,应该使用 System.out.print() 方法而不是 System.out.println() 方法,因为题目要求输出的元素之间用空格隔开,最后一个元素后不需要空格。修改代码如下:
```
if (flag == 0) {
for (int i = 0; i < arr1.length; i++) {
if (i < arr1.length - 1)
System.out.print(Integer.parseInt(arr1[i] + " ") + " ");
else
System.out.print(Integer.parseInt(arr1[i] + ""));
}
} else if (flag == 1) {
for (int i = arr1.length - 1; i >= 0; i--) {
if (i > 0)
System.out.print(Integer.parseInt(arr1[i] + " ") + " ");
else
System.out.print(Integer.parseInt(arr1[i] + ""));
}
}
```
阅读全文