[英]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.