在java集合中 我应该将用户输入作为整数并按升序排序。
import java.util.*;
import java.io.*;
class ArrayToCollection{
public static void main(String args[]) throws IOException{
BufferedReader in = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("How many elements you want to add to the array: ");
int n = Integer.parseInt(in.readLine());
int[] num = new int[n];
for(int i = 0; i < n; i++){
num[i] = in.readLine();
}
TreeSet<String> setA =new TreeSet<String>();
setA.add(num);
System.out.println(setA.contains(num));
}
}
答案 0 :(得分:2)
更改您的代码:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many elements you want to add to the array: ");
int n = Integer.parseInt(in.readLine());
System.out.println("enter numbers : ");
TreeSet<String> setA = new TreeSet<String>();
for (int i = 0; i < n; i++) {
setA.add(in.readLine());
}
System.out.println(setA.toString());
你不需要数组int
答案 1 :(得分:-1)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.TreeSet;
class ArrayToCollection{
public static void main(String args[]) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many elements you want to add to the array: ");
int n = Integer.parseInt(in.readLine());
System.out.println("enter numbers : ");
TreeSet<Integer> setA = new TreeSet<Integer>();
for (int i = 0; i < n; i++) {
setA.add(Integer.parseInt(in.readLine()));
}
System.out.println(setA.toString());
}
}