簡體   English   中英

從文本文件讀入,字符數限制

[英]Reading in from a text file, with character limit

我正在嘗試從文本文件中讀取文本,應該讀取僅由空格分隔的每個單詞(即忽略其他所有內容)。

因此,現在,我正在讀取掃描儀中的每個單詞並將其添加到列表中。 然后,我僅在添加到Secondarylist的字符數不存在100個字符的情況下,才嘗試從列表添加到SecondarrayList。

是的,我正在嘗試迭代第一個列表,並確保每個可容納100個字符以下的單詞都符合每個列表的限制,並且不會在中間添加單詞或打散單詞

我跑了這個:

for (int i = 0; i < SecondarrayList.size(); i++) {
            System.out.println(SecondarrayList.get(i));
        }

但沒有發生任何事情:/

    Scanner input = null;
        try {
            input = new Scanner(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        List<String> list = new ArrayList<String>();
        ArrayList<String> SecondarrayList = new ArrayList<String>();

        String word = null;
        while (input.hasNext()) {
            word = input.next();
            // System.out.println(word);
            list.add(word + " ");

        }

        for (int i = 0; i < list.size(); i++) {
            // System.out.println(list.get(i));

            do {
                SecondarrayList.add(list.get(i));

            } while (findlenghtofListinChars(SecondarrayList) < 100);

        }

        for (int i = 0; i < SecondarrayList.size(); i++) {
            System.out.println(SecondarrayList.get(i));
        }

    }

}

// returns number of length of chars
public static int findlenghtofListinChars(ArrayList<String> arrayL) {

    StringBuilder str = new StringBuilder("");
    for (int i = 0; i < arrayL.size(); i++) {
        // System.out.print(arrayL.get(i));

        str = str.append(arrayL.get(i));

    }

    return str.length();

}

打印單詞時的示例輸出(我們也可以忽略“,”,“ /”其他所有單詞,也可以忽略空格)

small 
donations 
($1 
to 
$5,000) 
are 
particularly 
important 
to 
maintaining 
tax 
exempt 

試試這個,我想你想做這樣的事情:

 Scanner input = null;
  try {
      input = new Scanner(new File(file));
  } catch (FileNotFoundException e) {
      e.printStackTrace();
  }

  List<String> list = new ArrayList<String>();
  ArrayList<String> SecondarrayList = new ArrayList<String>();

  String word = null;
  while (input.hasNext()) {
      word = input.next();
      list.add(word);
  }

  int totalSize = 0;

  for (String eachString : list) {

        totalSize +=eachString.length();

        if(totalSize >=100){
            break;
        }else{
          SecondarrayList.add(eachString);
        }
  }

  for (int i = 0; i < SecondarrayList.size(); i++) {
      System.out.println(SecondarrayList.get(i));
  }

}

在這種情況下,代碼的問題是您使用的條件始終為true的while循環。

這是因為您提供的輸入的字符長度約為80,始終小於100

因此,我建議將您的while循環更改為if語句,例如

do {
    SecondarrayList.add(list.get(i));
} while (findlenghtofListinChars(SecondarrayList) < 100);

會變成

if(findlenghtofListinChars(SecondarrayList) < 100){
    SecondarrayList.add(list.get(i);
}else{
    break;
}

暫無
暫無

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

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