簡體   English   中英

在數組列表中輸入數據而不在Java中使用數組

[英]input data in an arraylist without using an array in java

我在Java中不是很好,並且我想使我的代碼更好。我正在嘗試輸入一個句子,然后將該句子拆分為單詞,然后將單詞存儲在arraylist中。然后我必須輸入單詞並檢查是否句子中找到了單詞。到目前為止,我已經成功地做到了,代碼也起作用了。但是,我以后不使用數組,所以我不想使用數組,所以這是多余的。有沒有辦法因為我可以不使用數組直接在arraylist中輸入單詞?

  here are my codes:
   public static void main(String[] args){
    //the user is asked to enter a sentence
     Scanner input=new Scanner(System.in);
     System.out.println("enter a sentence");
        String text=input.nextLine();

        //the sentence is split
        String[] s=text.split("[[\\s+]*|[,]*|[\\.]]");

         ArrayList<String> list=new ArrayList<String>();
          //the word are stored into a variable then added into the array
            for(String ss:s){
                list.add(ss);
                }

          System.out.println("enter a word");
          String word=input.next();
            //check if the word is in the arraylist
           for(int i=0;i<list.size();i++){
            if(word.equals(list.get(i))){
              System.out.println("the word is found in the sentence");
                  System.exit(0);
          }

        }
        System.out.println("the word is not found in the sentence");

      }

一種選擇是遍歷text.split()返回的數組中的所有元素。 所以:

ArrayList<String> list = new ArrayList<String>();
for(String s : text.split("[[\\s+]*|[,]*|[\\.]]")){
    list.add(s);
}

拆分字符串創建的數組是必需的 ,但是可以用一行代碼創建ArrayList,這將允許在運行垃圾收集器時將其丟棄。

ArrayList<String> list = new ArrayList<Element>(Arrays.asList(text.split("[[\\s+]*|[,]*|[\\.]]")));

但是需要注意的重要一點是,text.split仍在創建數組。

使用Arrays.asList(..)Arrays.asList(..)后的輸入字符串創建列表。

String[] s=text.split("[[\\s+]*|[,]*|[\\.]]");
List<String> list = Arrays.asList(s);

然后只需使用List.contains(Object)來檢查是否包含輸入的單詞。

if(list.contains(word)){
   ...
}

因此最終程序將如下所示

public static void main(String[] args) {
    // the user is asked to enter a sentence
    Scanner input = new Scanner(System.in);

    System.out.println("enter a sentence");
    String text = input.nextLine();

    // the sentence is split
    String[] splittedSentence = text.split("[[\\s+]*|[,]*|[\\.]]");

    List<String> words = Arrays.asList(splittedSentence); // the word are stored into a variable then added into the array

    System.out.println("enter a word");
    String word = input.next();

    // check if the word is in the list
    if (words.contains(word)) {
        System.out.println("the word is found in the sentence");
    } else {
        System.out.println("the word is not found in the sentence");
    }
}

如果您真的想StringTokenizer數組StringTokenizer ,請看一下StringTokenizer

new StringTokenizer(text, ", .\t\n\r");

暫無
暫無

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

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