从具有字符限制

时间:2016-01-19 06:44:12

标签: java

我试图从文本文件中读取文本,它应该读入仅由空格分隔的每个单词(即忽略其他所有单词)。

所以现在,我正在读取扫描仪中的每个单词并将其添加到列表中。然后,我只是在添加到Secondarylist的字符数不存在100个字符时,尝试从列表添加到SecondarrayList。

是的,我正在尝试迭代第一个List,并确保每个可容纳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 

2 个答案:

答案 0 :(得分:1)

试试这个,我想你想做这样的事情:

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

}

答案 1 :(得分:0)

在这种情况下,代码的问题在于您正在使用while循环,其条件始终为true。

这是因为你给它的输入字符长度约为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;
}