2015-10-26 25 views
-3

在java集合 我應該得到用戶輸入爲整數並按升序排序。按用戶輸入的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)); 
    } 
} 
+2

什麼是你的問題?預期的結果是什麼?什麼是實際結果? –

+0

(請不要太過分了,OP是新的,並且顯示了他的嘗試。) –

回答

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

+0

** Brian Tompsett **謝謝 –

-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()); 
} 
}