簡體   English   中英

用戶輸入的 Java 集合

[英]Java Collections by user input

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

像這樣改變你的代碼:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM